【发布时间】:2011-07-14 10:53:32
【问题描述】:
我希望 ModelForm 中的 ChoiceField 有一个空白选项 (-----),但这是必需的。
我需要有空白选项以防止用户意外跳过该字段,从而选择错误的选项。
【问题讨论】:
标签: django django-forms
我希望 ModelForm 中的 ChoiceField 有一个空白选项 (-----),但这是必需的。
我需要有空白选项以防止用户意外跳过该字段,从而选择错误的选项。
【问题讨论】:
标签: django django-forms
您还可以覆盖表单的__init__() 方法并修改choices 字段属性,重新签名一个新的元组列表。 (这可能对动态变化有用):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_field'].choices = [('', '---------')] + self.fields['my_field'].choices
【讨论】:
这至少适用于 1.4 及更高版本:
CHOICES = (
('', '-----------'),
('foo', 'Foo')
)
class FooForm(forms.Form):
foo = forms.ChoiceField(choices=CHOICES)
Since ChoiceField is required (by default), it will complain about being empty when first choice is selected and wouldn't if second.
这样做比 Yuji Tomita 展示的方式更好,因为这样你就可以使用 Django 的本地化验证消息。
【讨论】:
您可以使用clean_FOO 验证该字段
CHOICES = (
('------------','-----------'), # first field is invalid.
('Foo', 'Foo')
)
class FooForm(forms.Form):
foo = forms.ChoiceField(choices=CHOICES)
def clean_foo(self):
data = self.cleaned_data.get('foo')
if data == self.fields['foo'].choices[0][0]:
raise forms.ValidationError('This field is required')
return data
如果是 ModelChoiceField,您可以提供 empty_label 参数。
foo = forms.ModelChoiceField(queryset=Foo.objects.all(),
empty_label="-------------")
这将保持所需的表单,如果选择-----,将引发验证错误。
【讨论】:
在参数中添加 null = True
喜欢这个
gender = models.CharField(max_length=1, null = True)
http://docs.djangoproject.com/en/dev/ref/models/fields/
您的意见
THEME_CHOICES = (
('--', '-----'),
('DR', 'Domain_registery'),
)
theme = models.CharField(max_length=2, choices=THEME_CHOICES)
【讨论】: