Django验证格式化日期



我在django表单上使用jquery.ui.datepicker。

我将日期格式化为:DateInput(format='%b %d, %Y')

在模型中定义为:models.DateField(default=datetime.now, blank=True)

但是格式化为'Aug 6, 2014'的日期失败。我如何让它验证形式save方法?

您可以在表单中使用clean方法来检查字段。假设datefield名为mydate,你可以在你的表单中编写一个名为def clean_mydate(dict)的方法,并在那里检查日期,如果你需要它,就会引发任何错误。

这是验证表单字段的正确方法。

https://docs.djangoproject.com/en/dev/ref/forms/validation/cleaning-and-validating-fields-that-depend-on-each-other

或者如果你想重写你的表单保存方法,你需要在你的表单中添加这样的东西:

def save(self, commit=True):
    instance = super(MyForm, self).save(commit=False)
    my_date= self.cleaned_data['mydate']
     // do some checks and raise errors
    if commit:
        instance.save()
    return instance

最新更新