Blank option in required ChoiceField

我怕爱的太早我们不能终老 提交于 2019-12-21 07:41:04

问题


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.


回答1:


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.




回答2:


You could validate the field with 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

If it's a ModelChoiceField, you can supply the empty_label argument.

foo = forms.ModelChoiceField(queryset=Foo.objects.all(), 
                    empty_label="-------------")

This will keep the form required, and if ----- is selected, will throw a validation error.




回答3:


You can also override form's __init__() method and modify the choices field attribute, reasigning a new list of tuples. (This may be useful for dynamic changes):

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_field'].choices = [('', '---------')] + self.fields['my_field'].choices



回答4:


in argument add null = True

like this

gender = models.CharField(max_length=1, null = True)

http://docs.djangoproject.com/en/dev/ref/models/fields/


for your comment

THEME_CHOICES = (
    ('--', '-----'),
    ('DR', 'Domain_registery'),
)
    theme = models.CharField(max_length=2, choices=THEME_CHOICES)


来源:https://stackoverflow.com/questions/5289491/blank-option-in-required-choicefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!