这里有很多很好的答案,但是我仍然不完全满意这些实现。我也有点沮丧,因为从不同来源(外键、选项)选择小部件会产生不同的行为。
我有一个设计,我正在和where select字段一起工作
总是
有一个空白选项,如果需要,它们旁边会有一个星号,如果它们是空的,表单将不会验证。也就是说,我只能正确地覆盖字段的空标签
TypedChoiceField
S.
结果是这样的
应该
看起来像。第一个结果总是字段的名称-在我的例子中,
label
.
这就是我最后做的。以下是重写的
__init__
我的表格方法:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for _, field in self.fields.items():
if hasattr(field, 'empty_label'):
field.empty_label = field.label
if isinstance(field, forms.TypedChoiceField):
field.choices = [('', field.label)] + [choice for choice in field.choices if choice[0]]