在Django 1.11中使用SelectDateWidget的空选择 [英] Empty choice with SelectDateWidget in django 1.11

查看:51
本文介绍了在Django 1.11中使用SelectDateWidget的空选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于SelectDateWidget,Django文档规定以下内容:

For the SelectDateWidget, Django documentation states the following:

如果不需要DateField,则SelectDateWidget将为空选择位于列表顶部(默认情况下为-).你可以使用empty_label属性更改此标签的文本.empty_label可以是字符串,列表或元组.当使用字符串时,所有选择框都将带有该标签的空选择.如果empty_label是3个字符串元素的列表或元组,选择框将有自己的自定义标签.标签应按此顺序排列("year_label","month_label","day_label").

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').

但是,我不清楚如何在必填的日期字段中设置空选项?我认为这不是一种罕见的情况:没有空的选择,但是预先选择了默认值,就可以轻松跳过所需的日期字段,并在不注意的情况下将其保存为默认值.

However, it is not clear to me how to set empty choice with the required date field? I assume this is not a rare situation: without the empty choices, but with default values preselected, one can easily skip the required date field and save it with the default values without noticing.

有人知道该怎么做吗?

推荐答案

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

I was able to do this by subclassing SelectDateWidget and overriding 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相似:

This answer is similar to GwynBleidD's from the thread here: Display empty_label on required selectDateWidget on Django, but updated to work with more recent versions of Django.

这篇关于在Django 1.11中使用SelectDateWidget的空选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆