[Django]-Empty label in widget Select

3👍

empty_label is a property of the field, not the widget. You already have a label set for position.

10👍

There are two ways to implement empty_label:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['field_name'].empty_label = "(Select here)"
        self.fields['field_name'].widget.attrs['class'] = 'main'
        self.fields['field_name'].queryset = Position.objects.all().values_list('id', 'position')

//OR   

class MyForm(forms.ModelForm):
    field_name = forms.ModelChoiceField(
        queryset=Position.objects.all().values_list('id', 'position'), 
        empty_label="(Select here)"
        )

    class Meta:
        model = MyModel

0👍

from the Django Documentation https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.SelectDateWidget

If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is — by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order (‘year_label’, ‘month_label’, ‘day_label’).

Leave a comment