我在表单中使用了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')让它不可选的最简单的方法是什么,或者至少在用户选择它时给出一个错误?
发布于 2010-02-13 11:40:38
如果选择了任何分隔符,您可以编写一个干净的方法来引发验证错误。
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 发布于 2014-12-04 07:53:00
您可以使用以下命令: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')),
)
),
]发布于 2016-10-08 11:12:26
我不知道您使用的是哪个版本的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'),
...
)这就是我使用的全部内容,如果用户在下拉菜单中选择了任何一个值为“None”的列表项,它就会对用户说“这个字段是必需的”。
现在..。当然,在我的项目中,选择列表正在我的whatever.com/admin页面中使用,但这可能并不相关。然而,相关的是,您必须确保您的模型(或表单)类字段不包含"blank = True“。默认情况下,如果省略它,它应该为false,换句话说,该字段不接受null或空字符串值。这应该就是你所需要的.
https://stackoverflow.com/questions/2256010
复制相似问题