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 t
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.