Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty label in widget Select

Here in Forms we can use the empty_label. I use widget Select, my choices are from database, does it possible to use here empty_label? In model I have:

position = forms.IntegerField(label=position_label, required=False, 
    widget=forms.Select(choices=Position.objects.all().values_list('id', 'position'),
    attrs={'class':'main', 'title': position_label},
    ), empty_label="(Empty)")

But the error is:

TypeError: __init__() got an unexpected keyword argument 'empty_label'

How to set the label to 'Empty'?

like image 923
Lev Avatar asked Dec 02 '25 05:12

Lev


2 Answers

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
like image 121
catherine Avatar answered Dec 04 '25 19:12

catherine


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

like image 44
Brandon Avatar answered Dec 04 '25 21:12

Brandon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!