简体   繁体   中英

Django Form Choice Field Value Not Selected when Editing Instance

I have a simple form that I'm using to update data.

All data are correctly loaded from the DB, however the current value from my choice field (pull down menu) is the only one not being initially selected with current value.

My Django Form:

class MyForm(forms.ModelForm):  

def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)

choices = (
  ('', 'Select'),
  ('1', 'Option 1'),
  ('2', 'Option 2'),
  )

self.fields['myfield'] = forms.ChoiceField(
                        required=True,
                        error_messages = {'required': 'Field is Required!'},
                        label='My Label',
                        choices=choices,)
...

My goal is to have the current value selected. For example, if the current value is 2 I would like to have the Option 2 selected on initial load as with the current form, the initial instance value is for some reason not selected.

I think you have misunderstood initial values and instance 's value.

Supposed you have a model instance which myfield = '2' , you do not need to hijack the form under __init__() , instead just declare the choices under forms.ChoiceField , and it will work.

Look at this example:

In [1]: from django import forms

In [2]: from django.db import models

In [3]: class MyModel(models.Model):
   ...:     myfield = models.CharField(max_length=5, blank=True, default='')
   ...:     class Meta:
   ...:         app_label='test'

In [4]: class MyForm(forms.ModelForm):
   ...:     choices = (('', 'Select'), ('1', 'Option 1'), ('2', 'Option 2'),)
   ...:     myfield = forms.ChoiceField(choices=choices)
   ...:     class Meta:
   ...:         model = MyModel
   ...:         fields = ['myfield']
   ...:

In [5]: a = MyModel(myfield='2')

In [6]: f = MyForm(instance=a)

In [7]: print f
<tr><th><label for="id_myfield">Myfield:</label></th><td><select id="id_myfield" name="myfield">
<option value="">Select</option>
<option value="1">Option 1</option>
<option value="2" selected="selected">Option 2</option>
</select></td></tr>

As you can see, the forms field myfield will be Selected .

If the values provided by the instance are not included as acceptable choices as defined in the model, then the form will NOT inherit the values from the instance of the model, and instead the form will behave the same as a blank form.

(Thanks also to WayBehind comment)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM