所需ChoiceField中的空白选项

wil*_*ill 11 django django-forms

我希望ModelForm中的ChoiceField有一个空白选项(------)但它是必需的.

我需要有空白选项,以防止用户意外跳过该字段,从而选择错误的选项.

Ctr*_*l-C 23

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

CHOICES = (
    ('', '-----------'),
    ('foo', 'Foo')
)

class FooForm(forms.Form):
    foo = forms.ChoiceField(choices=CHOICES)
Run Code Online (Sandbox Code Playgroud)

由于ChoiceField是必需的(默认情况下),因此在选择第一个选项时会抱怨为空,如果是第二个选择则不会.

这样做比Yuji Tomita显示的方式更好,因为这样你就可以使用Django的本地化验证消息了.


Yuj*_*ita 6

您可以使用以下方式验证字段 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
Run Code Online (Sandbox Code Playgroud)

如果它是ModelChoiceField,则可以提供empty_label参数.

foo = forms.ModelChoiceField(queryset=Foo.objects.all(), 
                    empty_label="-------------")
Run Code Online (Sandbox Code Playgroud)

这将保留所需的表单,如果-----选中,将抛出验证错误.