[英]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:我的 Django 表单:
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.例如,如果当前值为2
我希望在初始加载时选择Option 2
与当前表单一样,初始实例值由于某种原因未选择。
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.假设您有一个myfield = '2'
的模型实例,您不需要劫持__init__()
下的表单,而只需在forms.ChoiceField
下声明choices
,它就会起作用。
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 .如您所见,表单字段myfield
将是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) (也感谢 WayBehind 评论)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.