Django, ModelChoiceField() and initial value

后端 未结 6 2091
灰色年华
灰色年华 2020-12-04 12:14

I\'m using something like this:

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

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

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 12:27

    If you want to set the default initial value you should be defining initial like other form fields except you set it to the id instead.

    Say you've got field1 like this:

    class YourForm(forms.Form):
        field1 = forms.ModelChoiceField(queryset = MyModel.objects.all() )
    

    then you need to set initial when you create your form like this:

    form = YourForm(initial = {'field1': instance_of_mymodel.pk })
    

    rather than:

    form = YourForm(initial = {'field1': instance_of_mymodel })
    

    I'm also assuming you've defined __unicode__ for your models so this displays correctly.

提交回复
热议问题