Django, ModelChoiceField() and initial value

Viewed 84253

I'm using something like this:

field1 = forms.ModelChoiceField(queryset=...)

How can I make my form show the a value as selected?

7 Answers
field1 = forms.ModelChoiceField(queryset=Model.objects.all(), empty_label="Selected value")

It's as simple as that....!

Just want to add this answer after stumbling on this question. I know it works on Django 3.2, at least. If you have some calculated value in the __init__ method, you can do this to set the initial value at instantiation as well:

def __init__(self, value, *args, **kwargs):
    # super call, etc.
    self.do_something(value)
    self.fields['field'].initial = value

If the form does multiple things with value, it's a bit more DRY to pass it only once instead of redundantly with the initial kwarg in instantiation.

Related