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'?
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
empty_label is a property of the field, not the widget. You already have a label set for position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With