Django, ModelChoiceField() and initial value

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 12:33

    You can just use

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

    to make the first value selected etc. It's more generic way, then the other answer.

    0 讨论(0)
  • 2020-12-04 12:35

    You could do this as well:

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

    if you are parsing your primary key through a query string or via an ajax call no need for an instance, the query set has already handled that for your drop down, the pk indexes the state you want

    0 讨论(0)
  • 2020-12-04 12:43

    The times they have changed:

    The default initial value can now be set by defining initial like other form fields except you set it to the id instead.

    Now this will suffice:

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

    Though both still work.

    0 讨论(0)
  • 2020-12-04 12:49
    field1 = forms.ModelChoiceField(queryset=Model.objects.all(), empty_label="Selected value")
    

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

    0 讨论(0)
提交回复
热议问题