Django, ModelChoiceField() and initial value

后端 未结 6 2012
灰色年华
灰色年华 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

    The code

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

    and

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

    or initial field directly following:

    field1 = forms.ModelChoiceField(queryset=..., initial=0) 
    

    All work.

    The first two ways will override the final way.

提交回复
热议问题