小部件选择中的空标签

3 投票
3 回答
11427 浏览
提问于 2025-04-17 17:59

在表单中,我们可以使用 empty_label。我使用的是 Select 这个控件,我的选项是从数据库中来的,请问这里可以使用 empty_label 吗?在我的模型中有:

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)")

但是出现了这个错误:

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

怎么把标签设置为 'Empty' 呢?

3 个回答

0

来自Django文档的内容 https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#django.forms.SelectDateWidget

如果DateField这个字段不是必填的,那么SelectDateWidget在列表的最上面会有一个空选项(默认是---)。你可以通过empty_label这个属性来改变这个空选项的文字。empty_label可以是一个字符串、列表或元组。如果用字符串的话,所有的选择框都会显示这个空选项的文字。如果empty_label是一个包含3个字符串元素的列表或元组,那么每个选择框就会有自己独特的标签。这个标签的顺序应该是('year_label', 'month_label', 'day_label')。

10

实现 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
3

empty_label 是字段的一个属性,而不是小部件的属性。你已经为 position 设置了一个 label

撰写回答