以卡尔的回答为指导,在围绕Django源搜索了几个小时后,我认为这是完整的解决方案:
-
要删除空选项(扩展Carl的示例):
class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = None
# following line needed to refresh widget copy of choice list
self.fields['verb'].widget.choices =
self.fields['verb'].choices
-
要自定义空选项标签,基本上是相同的:
class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = "Select a Verb"
# following line needed to refresh widget copy of choice list
self.fields['verb'].widget.choices =
self.fields['verb'].choices
我认为这种方法适用于所有将modelchoiceFields呈现为HTML的场景,但我并不乐观。我发现当初始化这些字段时,它们的选择会传递到select小部件(请参见django.forms.fields.choiceField.\u set_choices)。初始化后设置空的_标签不会刷新选择小部件的选择列表。我对Django不够熟悉,不知道这是否应该被视为bug。