编辑实例时未选择Django表单选择字段值 [英] Django Form Choice Field Value Not Selected when Editing Instance

查看:54
本文介绍了编辑实例时未选择Django表单选择字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于更新数据的简单表格.

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.

我的Django表单:

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,)
...

我的目标是选择当前值.例如,如果当前值是 2 ,我希望像当前​​表单一样在初始加载时选择 Option 2 ,则由于某种原因,初始实例值不是选择.

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.

假定您有一个 myfield ='2'的模型实例,则无需劫持 __ init __()下的表单,只需声明选择 forms.ChoiceField 下的,它将起作用.

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.

看这个例子:

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>

如您所见,表单域 myfield 将被选中.

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

这篇关于编辑实例时未选择Django表单选择字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆