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

2đź‘Ť

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

👤AlvaroAV

Leave a comment