gpt4 book ai didi

python - 在 Django 1.11 中使用 SelectDateWidget 的空选择

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:40 25 4
gpt4 key购买 nike

对于 SelectDateWidget,Django 文档说明如下:

If the DateField is not required, SelectDateWidget will have an empty choice at the top of the list (which is --- by default). You can change the text of this label with the empty_label attribute. empty_label can be a string, list, or tuple. When a string is used, all select boxes will each have an empty choice with this label. If empty_label is a list or tuple of 3 string elements, the select boxes will have their own custom label. The labels should be in this order ('year_label', 'month_label', 'day_label').

但是,我不清楚如何使用所需的日期字段设置空选择?我认为这不是一种罕见的情况:如果没有空选择,但使用预选的默认值,人们可以轻松地跳过所需的日期字段并使用默认值保存它,而不会引起注意。

有人知道怎么做吗?

最佳答案

我能够通过子类化 SelectDateWidget 并覆盖 get_context 来做到这一点。

class MySelectDateWidget(SelectDateWidget):

def get_context(self, name, value, attrs):
old_state = self.is_required
self.is_required = False
context = super(MySelectDateWidget, self).get_context(name, value, attrs)
self.is_required = old_state
return context

这个答案类似于 GwynBleidD 在此处线程中的答案:Display empty_label on required selectDateWidget on Django , 但已更新以与更新版本的 Django 一起使用。

关于python - 在 Django 1.11 中使用 SelectDateWidget 的空选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com