问题描述
根据Django在SelectDateWidget上的文档(),如果 empty_label
如果 DateField
不是必需的。我注意到如果需要 DateField
,则小部件上的默认值将为 January
, 1
和< current-year>
。有没有一种方法可以使 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!