YPCrumble
YPCrumble

Reputation: 28722

Is there a way to put an empty_label in a Django Select field for a non-modelform?

I want to use a placeholder in a Django Select field, but I don't want to include it in the options.

I've created an empty field like so: https://stackoverflow.com/a/6085935/2532070

choices = [(u'', u'Select Year')]
choices.extend([(unicode(year), unicode(year)) for year in range(1970, 2015)])
graduation = forms.ChoiceField(choices=choices)

And this answer covers the empty_label argument of a ModelForm: Customize/remove Django select box blank option

But mine is a regular Django form. Is there a way to make the default button render "Select Year" but not include "Select Year" in the dropdown list? Thanks!

Upvotes: 1

Views: 4020

Answers (1)

AlvaroAV
AlvaroAV

Reputation: 10563

Are you trying to add some kind of autocomplete to the form field ? I'll tell you 2 different ways to do this, but depending on what are you trying to do one is better than the other.

First Way

This way is the "generic", if you're trying to use something like select2 your best answer is the second way

choices = [
    (u'', u'Select Year'),
    (u'1', u'1231'),
    (u'2', u'1232')
    (u'3', u'1233')
]
class your_form(forms.Form):

    year = forms.ChoiceField(choices=YEAR_CHOICES, required=False)

    def __init__(self, *args, **kwargs):
        super(your_form, self).__init__(*args, **kwargs)            
        self.fields['year'].queryset = YEAR_MODEL.objects.none()
        self.fields['year'].widget = forms.TextInput(attrs={'placeholder': _(u'Select Year')})

Second Way

If you're trying to add a select2 via AJAX you need to receive a non-select field in the template, so you'll need something like:

class your_form(forms.Form):

    year = forms.CharField(max_length=255, required=False)

    def __init__(self, *args, **kwargs):
        super(your_form, self).__init__(*args, **kwargs)            
        self.fields['year'].widget = forms.TextInput(attrs={'placeholder': _(u'Select Year')})

The difference between the first way and the second is that the first way the field year is a ChoiceField that we overwrite the __init__ function to make the selector empty, and the second one is just a CharField that we can manage as we need (this way is just in case you're trying to use a select2 Autocomplete via AJAX)

In both examples we initialize the text box using:

self.fields['year'].widget = forms.TextInput(attrs={'placeholder': _(u'Select Year')})

inside the __init__ overwrite

Upvotes: 2

Related Questions