问题描述
根据 Django 在 SelectDateWidget 上的文档 (https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#selectdatewidget),如果不需要 DateField
,将显示 empty_label
.我注意到如果 DateField
是必需的,小部件上的默认值将是 January
、1
和 ;.有没有办法使
DateField
成为必需,但在初始表单上显示带有 empty_label
(例如 -----)的小部件?
According to Django's Doc on SelectDateWidget (https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#selectdatewidget), the
empty_label
will be shown if the DateField
is not required. I noticed if the DateField
is required, the default value on the widget will be January
, 1
, and <current-year>
. Is there a way to make the DateField
required, but showing the widget with empty_label
(such as -----) on the initial form?
推荐答案
不幸的是,
SelectDateWidget
中的空标签仅在不需要字段时使用,但您可以通过子类化 来简单地更改此设置SelectDateWidget
和覆盖 create_select
方法:
Unfortunately, empty label in
SelectDateWidget
is only used if field is not required, but you can simply change this by subclassing SelectDateWidget
and overriding create_select
method:
class MySelectDateWidget(SelectDateWidget):
def create_select(self, *args, **kwargs):
old_state = self.is_required
self.is_required = False
result = super(MySelectDateWidget, self).create_select(*args, **kwargs)
self.is_required = old_state
return result
但在这种情况下,您可能还必须覆盖对您的字段的验证,因此它会抛出该字段是必需的错误,而不是当 select 保留为空白值时该选择无效.
But in that case you may have to override also validation of your field, so it will throw error that field is required, not that choice is invalid when select is left on blank value.
这篇关于在 Django 上所需的 selectDateWidget 上显示 empty_label的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!