lazarea
lazarea

Reputation: 1329

Adding placeholder to ChoiceField in Django?

In my forms.py I have a simple form class defined as:

SAMPLE_STRINGS = ['aa','ab','bb','c0']

class IndicatorForm(forms.Form):
    chosen_number = forms.IntegerField(label='Please select a value')
    chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True)

I want to add a placeholder for both fields. For the first one, it was easy:

chosen_number = forms.IntegerField(label='Please select a value', widget=forms.NumberInput(attrs={'placeholder': 0}))

But for the ChoiceField, I didn't have any luck. I tried using widget=forms.TextInput(attrs=...) but that removes the choices and transforms the field into a simple text field. widget=forms.ChoiceInput and widget=forms.ChoiceField do not work either.

How can I add a placeholder saying "Select..." to my ChoiceField?

Upvotes: 2

Views: 2743

Answers (1)

elyas
elyas

Reputation: 1415

For a ModelChoiceField Django performs this operation automatically and gives you an optional override argument empty_label.

For a ChoiceField you have to add your empty label manually. If you want the same default empty label we can insert it by copying what Django does:

from django.db.models.fields import BLANK_CHOICE_DASH

...

chosen_string = forms.ChoiceField(choices=BLANK_CHOICE_DASH + SAMPLE_STRINGS, label='Please select a string', required=True)

For a custom empty label you can simply prepend a two-tuple to your SAMPLE_STRINGS list:

SAMPLE_STRINGS = [('', 'My empty label'), 'aa', 'ab', 'bb', 'c0']

The two-tuple ensures value="" in the resulting <option> generated.

Upvotes: 6

Related Questions