我在我的表单中使用ChoicesField
,但我想在其中放置一个分隔符:
COUNTRIES = (
('CA', _('Canada')),
('US', _('United States')),
(None, _('---')), # <----------
('AF', _('Afghanistan')),
('AX', _('Aland Islands')),
('AL', _('Albania')),
('DZ', _('Algeria')),
('AS', _('American Samoa')),
# ...
class AddressForm(forms.Form):
country = forms.ChoiceField(choices=COUNTRIES, initial='CA')
最简单的方法是让这种方式无法选择,或者至少在用户选择时会出错?
答案 0 :(得分:1)
如果选择了任何分隔符,您可以编写一个干净的方法来引发验证错误。
class AddressForm(forms.Form):
country = forms.ChoiceField(choices=COUNTRIES, initial='CA')
def clean_country(self):
data = self.cleaned_data["country"]
if not data:
raise forms.ValidationError("You must select a valid country.")
return data
答案 1 :(得分:1)
您可以使用:https://docs.djangoproject.com/en/dev/ref/models/fields/#field-choices
你可以这样格式化:
COUNTRIES = [
("CA", _("Canada")),
("US", _("United States")),
# This format will indent the nested tuples over and the
# "-----" will be un-selectable
#
("---------------", ( # This will be a header for the items nested below
("AF", _("Afghanistan")),
('AX', _('Aland Islands')),
('AL', _('Albania')),
('DZ', _('Algeria')),
('AS', _('American Samoa')),
)
),
]
答案 2 :(得分:1)
我不知道你使用的是什么版本的Django,但我使用的是1.10.1,我使用了以下内容:
ICONS = (
(None, ''),
(None, '==Extra Contact Info=='),
('phone', 'Phone'),
('phone', 'Phone (square)'),
('fax', 'Fax'),
('envelope', 'E-mail (black)'),
('envelope-o', 'E-mail (white/clear)'),
(None, ''),
(None, '==Social Media=='),
('facebook', 'Facebook'),
('facebook-official', 'Facebook (official)'),
('facebook-square', 'Facebook (square)'),
('google-plus', 'Google Plus'),
...
)
以及我使用的全部内容,如果用户在下拉菜单中选择了任何列表项,其中包含&#39;无&#39;在它的价值中,它会咆哮在用户说&#34;这个字段是必需的。&#34;
现在...当然在我的项目中,选择列表正在我的whatever.com/admin页面中使用,但这可能不相关。但是,相关的是,您必须确保您的模型(或表单)类字段不包含&#34; blank = True&#34;。默认情况下,如果省略它,它应该为false,换句话说,该字段不会接受null或空字符串值。这应该就是你所需要的......