在 Django 中向 ChoiceField 添加占位符?

laz*_*rea 1 django

在我的 forms.py 中,我有一个简单的表单类定义为:

SAMPLE_STRINGS = ['aa','ab','bb','c0']

class IndicatorForm(forms.Form):
    chosen_number = forms.IntegerField(label='Please select a value')
    chosen_string = forms.ChoiceField(choices=SAMPLE_STRINGS, label='Please select a string', required=True)
Run Code Online (Sandbox Code Playgroud)

我想为这两个字段添加占位符。对于第一个,很简单:

chosen_number = forms.IntegerField(label='Please select a value', widget=forms.NumberInput(attrs={'placeholder': 0}))
Run Code Online (Sandbox Code Playgroud)

但对于ChoiceField,我就没那么幸运了。我尝试使用widget=forms.TextInput(attrs=...),但这会删除选择并将该字段转换为简单的文本字段。widget=forms.ChoiceInput并且widget=forms.ChoiceField也不工作。

如何将显示“选择...”的占位符添加到我的 ChoiceField?

ely*_*yas 5

对于ModelChoiceFieldDjango,自动执行此操作并为您提供可选的覆盖参数empty_label

对于 a,ChoiceField您必须手动添加空标签。如果您想要相同的默认空标签,我们可以通过复制 Django 的操作来插入它:

from django.db.models.fields import BLANK_CHOICE_DASH

...

chosen_string = forms.ChoiceField(choices=BLANK_CHOICE_DASH + SAMPLE_STRINGS, label='Please select a string', required=True)
Run Code Online (Sandbox Code Playgroud)

对于自定义空标签,您只需在列表中添加一个二元组即可SAMPLE_STRINGS

SAMPLE_STRINGS = [('', 'My empty label'), 'aa', 'ab', 'bb', 'c0']
Run Code Online (Sandbox Code Playgroud)

二元组确保value=""生成结果<option>