Django ChoiceField Empty Option for Select/Dropdown

If you're looking to add a empty_label to your ChoiceField, like you can for ModelChoiceField (empty_label="All"), you're going to have to override __init__ on your form. This solution I found on StackOverflow works well.

COMPETITION_TYPE_CHOICES = (
(1, 'Olympic Games'),
(2, 'ISU Championships'),
(3, 'Grand Prix Series'),
)

class CompetitionSearchForm(forms.Form):
  name = forms.CharField(required=False)
  type = forms.ChoiceField(choices=COMPETITION_TYPE_CHOICES,required=False)

def __init__(self, *args, **kwargs):
  super(CompetitionSearchForm, self).__init__(*args, **kwargs)
  if not self.fields['type'].choices[0][0] == '':
    self.fields['type'].choices.insert(0, ('','---------' ) )


Next entry

Previous entry

Similar entries


Comments

Comments are closed.


Pingbacks

  1. [...] an earlier post we figured out how to add a default option to a Django ChoiceField within a form (forms.Form). The [...]

Pingbacks are open.


Trackbacks

Trackback URL