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 field?
Forms.py:
thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
color = forms.ChoiceField(choices=COLORS)
year = forms.ChoiceField(choices=YEAR_CHOICES)
I have tried the solutions suggested here:
Stack Overflow Q - Setting CHOICES = [('','All')] + CHOICES
resulted in an internal server error.
Stack Overflow Q2 - After defining ('', '---------'),
in my choices, still defaulted to the first item in the list, not the ('', '---------'),
choice.
Gist - Tried using EmptyChoiceField
defined here, but did not work using Django 1.4.
But none of these have worked for me.. How would you solve this issue? Thanks for your ideas!
Here's the solution that I used:
from myapp.models import COLORS
COLORS_EMPTY = [('','---------')] + COLORS
class ColorBrowseForm(forms.Form):
color = forms.ChoiceField(choices=COLORS_EMPTY, required=False, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))