简体   繁体   English

编辑实例时未选择 Django 表单选择字段值

[英]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.

相关问题 为什么 Django 表单选择字段不显示所选模型的初始值 - Why Django form choice field don't showing initial value from model as selected 选择特定选项后,如何更改 Django model 字段的值? - How can I change the value of a Django model field when a particular choice is selected? 更新实例时的Django Form字段初始值 - Django Form field initial value when updating an instance Django中的多选表单字段 - Multi choice form field in Django 当用户编辑表单字段时,从Django TimeField中删除秒 - Removing the seconds from a Django TimeField when a user is editing the form field 在 Django 中,根据模型中其他字段中选择的值删除选择字段下拉列表中的选项 - In Django, remove options in a choice-field dropdown based on the value selected in other field in a model 在django中使用图像字段进行表单编辑时,__init __()在django中获得了意外的关键字参数&#39;instance&#39; - __init__() got an unexpected keyword argument 'instance' in django at the time of form editing with image field in django Django:多选表单字段的验证器 - Django: Validator for a multiple choice form field Django将自定义验证添加到表单中的选择字段 - Django add custom validation to choice field in form 过滤表单的Django用户选择字段使用 - Filtering Django User Choice Field use for a form
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM