我似乎无法在表单的ModelChoiceField中重新标记空标签。 我试过了。 (注意我使用django crispy表单进行表单布局 - 不应该干扰它)
Forms.py
class PaymentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['payment_day'].empty_label = 'test something'
self.helper = FormHelper(self)
self.helper.label_class = 'sr-only'
self.helper.form_tag = False
self.helper.layout = Layout(
......
PrependedText('payment-day', '<i class="fa fa-calendar"></i>', placeholder="What"),
)
class Meta:
model = DirectDebit
fields = [
......
'payment_day',
]
models.py
class DirectDebit(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
......
DAYS_OF_MONTH_CHOICES = [(i, i) for i in range(32)]
payment_day = models.IntegerField(choices=DAYS_OF_MONTH_CHOICES)
time_stamp = models.DateField(auto_now=True)
答案 0 :(得分:0)
当您设置empty_label
时,可能为时已晚,因为已经计算了字段的选择。尝试将查询集重新分配给自己,以查看是否触发了重新计算的选择。
super().__init__(*args, **kwargs)
self.fields['payment_day'].empty_label = 'test something'
self.fields['payment_day'].queryset = self.fields['payment_day'].queryset
答案 1 :(得分:0)
解决:
self.fields['payment_day'].choices = [('', '---- Please select your payment day ----')] + list(
self.fields['payment_day'].choices[1:])