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 b
Solution 1:
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.dbimport models
In [3]: classMyModel(models.Model):
...: myfield = models.CharField(max_length=5, blank=True, default='')
...: classMeta:
...: app_label='test'In [4]: classMyForm(forms.ModelForm):
...: choices = (('', 'Select'), ('1', 'Option 1'), ('2', 'Option 2'),)
...: myfield = forms.ChoiceField(choices=choices)
...: classMeta:
...: model = MyModel
...: fields = ['myfield']
...:
In [5]: a = MyModel(myfield='2')
In [6]: f = MyForm(instance=a)
In [7]: print f
<tr><th><labelfor="id_myfield">Myfield:</label></th><td><selectid="id_myfield"name="myfield"><optionvalue="">Select</option><optionvalue="1">Option 1</option><optionvalue="2"selected="selected">Option 2</option></select></td></tr>
As you can see, the forms field myfield
will be Selected.
Solution 2:
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)
Post a Comment for "Django Form Choice Field Value Not Selected When Editing Instance"