1

我正在关注以在我的模型表单上添加自定义验证,并且它正在工作......主要是。

我的代码:

from django import forms
from django.utils.translation import ugettext_lazy as _
from datetime import datetime, timedelta

from datetimewidget.widgets import DateWidget

from .models import User

class UserForm(forms.ModelForm):

    class Meta:
        # Set this form to use the User model.
        model = User

        # Constrain the UserForm to just these fields.
        fields = ("birthdate")
        widgets = {
            'birthdate': DateWidget(attrs={'id':"id_birthdate"}, bootstrap_version=3)
        }

    def clean_birthdate(self):
        birthdate = self.cleaned_data["birthdate"]
        min_time = datetime.strptime('1920-01-01', '%Y-%m-%d').date()
        delta = birthdate - min_time
        if  delta <= timedelta(days=0):
            raise forms.ValidationError(_("We don't accept people born before 1920"))
        return birthdate

在 1900 年 1 月 1 日之前,它会像预期的那样引发错误,但是一旦我进入 1899 年它就不会。我不确定是什么原因造成的。我正在使用DateTimeWidget

我得到的错误是:

year=1899 is before 1900; the datetime strftime() methods require year >= 1900

我检查了比较的结果,它按预期工作(1920 年以下的年份为假)。

简而言之,模型正在更新,并且在应该时不会引发错误。

4

1 回答 1

1

这是 python 内置 strftime 函数的一个限制。它不支持 1900 年之前的日期。试试这个

if birthdate.year < 1920:
    raise forms.ValidationError(_("We don't accept people born before 1920"))
于 2014-09-17T22:22:47.330 回答