0

The question of how to supply an initial value in a ModelForm is well answered: Overriding initial value in ModelForm

But how do I stuff a value in after the model is created? Or how would I correct this code?

class Entry_form(forms.ModelForm):
    class Meta:
        model = models.Entry
        exclude = ('')

:

def entry_add(request, pk):
    form = Entry_form
    selected_text = request.GET.get('selected_text', '')
    form.fields['title'].initial = 'Test: ' + selected_text
    return render(request, 'entry_add,{'form': form})
Community
  • 1
  • 1
Bryce
  • 8,313
  • 6
  • 55
  • 73

1 Answers1

0

You have some errors in your code.

  1. Remove the line:

    exclude = ('')

    ('') is an empty string, not an empty tuple.

  2. form = Entry_form should be form = Entry_form()

  3. return render(request, 'entry_add,{'form': form}) - missing closing quote.

The line:

form.fields['title'].initial = 'Test: ' + selected_text

Is correct, and should work.

An alternative way is:

form.initial['title'] = 'Test: ' + selected_text
yprez
  • 14,854
  • 11
  • 55
  • 70