How do you make ChoiceField
\'s label behave like ModelChoiceField
? Is there a way to set an empty_label
, or at least show a blank fiel
A little late to the party..
How about not modifying the choices at all and just handling it with a widget?
from django.db.models import BLANK_CHOICE_DASH
class EmptySelect(Select):
empty_value = BLANK_CHOICE_DASH[0]
empty_label = BLANK_CHOICE_DASH[1]
@property
def choices(self):
yield (self.empty_value, self.empty_label,)
for choice in self._choices:
yield choice
@choices.setter
def choices(self, val):
self._choices = val
Then just call it:
class SomeForm(forms.Form):
# thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
color = forms.ChoiceField(choices=COLORS, widget=EmptySelect)
year = forms.ChoiceField(choices=YEAR_CHOICES, widget=EmptySelect)
Naturally, the EmptySelect
would be placed inside some kind of common/widgets.py
code and then when ever you need it, just reference it.