必需的ChoiceField中的空白选项 [英] Blank option in required ChoiceField

查看:67
本文介绍了必需的ChoiceField中的空白选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的ModelForm中的ChoiceField具有空白选项(------),但这是必需的。



我需要具有空白选项以防止用户

解决方案

这至少适用于1.4及更高版本:

 选择=(
('','-----------'),
( 'foo','Foo')


类FooForm(forms.Form):
foo = form.ChoiceField(choices = CHOICES)

由于ChoiceField是必填项(默认情况下),因此它会抱怨选择第一项时为空,如果选择第二项则为空。 / p>

最好这样做,这比Yuji Tomita展示的方法要好,因为这样可以使用Django的本地化验证消息。


I want my ChoiceField in ModelForm to have a blank option (------) but it's required.

I need to have blank option to prevent user from accidentally skipping the field thus select the wrong option.

解决方案

This works for at least 1.4 and later:

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.

It's better to do it like this than the way Yuji Tomita showed, because this way you use Django's localized validation messages.

这篇关于必需的ChoiceField中的空白选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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