【问题标题】:Override clean method to clean custom date field so it can accept month/year only or year only date data覆盖清理方法以清理自定义日期字段,以便它可以仅接受月/年或仅年日期数据
【发布时间】:2014-06-06 14:46:31
【问题描述】:

我想将日期数据显示并保存为以下形式之一:

  • 年月日
  • 年月

为了实现这一点,我有以下模型结构:

我有一个Model,结构如下

CHOICES = [
    (0, "Year/Month/Date"),
    (1, "Year/Month"),
    (2, "Year"),
]

class MyModel(Model):
    my_date = Models.DateField(...)
    my_date_format = Models.SmallIntegerField(choices=CHOICES)

而在ModelForm

class MyForm(ModelForm):
    class Meta:
    model = MyModel
    widgets = {"my_date": SelectDateWidget(required=False), }

我的逻辑如下:

  • 如果用户设置日、月和年;然后按原样保存日期并将my_date_format 设置为0。
  • 如果用户设置月份和年份(将日期留空);然后我将 day 设置为 1 并将 my_date_format 设置为 1,因此我将忽略 my_date 数据的 day 部分。
  • 如果用户设置年份(将日期和月份留空);然后我将日期和月份设置为 1 并将 my_date_format 设置为 2,因此我将在之后忽略 my_date 数据的日期和月份部分。

我的问题是表单验证。 SelectDateWidget 需要验证日期并将其强制转换为 python datetime.date 但我需要发布数据以检查哪个字段为空白以设置 my_date_format 值。

我必须将日期数据以date 的形式保存到我的数据库中,以便正确查询。

我应该如何覆盖form.clean() 方法?

【问题讨论】:

标签: python django


【解决方案1】:

我会尝试类似的。

免责声明:未经测试,但也许它可以为您提供想法。

def clean(self):
    cleaned_data = super(MyForm, self).clean()

    # Check the my_date_format value here
    ...

    # Then generate appropriate datetime according your own rules
    my_datetime = ...

    # Add datetime to the cleaned_data dictionnary
    cleaned_data['my_date'] = my_datetime

    return cleaned_data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2016-04-14
    相关资源
    最近更新 更多