Search code examples
djangodjango-forms

Django ChoicesField divider?


I'm using a ChoicesField in my form, but I want to put a divider in it like this:

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')

What's the easiest way to make that unselectable, or at least give an error if the user picks it?


Solution

  • You could write a clean method to raise a validation error if any divider is selected.

    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