【问题标题】:django forms dateField fails validationdjango forms dateField 验证失败
【发布时间】:2012-02-23 09:17:51
【问题描述】:

我正在尝试在 django 中验证用户分析表单,但我不能。 forms.dateField() 似乎有问题。它不验证(即 is_valid() 返回 false)

这是我的表单 dateField 条目: date_of_birth = forms.DateField(label=u'date of birth', input_formats='%d/%m/%Y', required=False, widget=forms.DateInput(format = '%d/%m/%Y'))

我注意到request.POST.get('date_of_birth', '') 返回了正确的日期(即我在 html 表单字段中输入的日期)。

我还注意到在这个函数中:

def clean_date_of_birth(self):
    date = self.cleaned_data['date_of_birth']

日期对象总是无。

我做错了什么?

编辑:

这是我要输入的内容: 29/07/1974(1974 年 7 月 29 日)

这是“提交”的输出(各种请求)

29/07/1974
profile form is *NOT* valid
[23/Feb/2012 12:16:27] "POST /profile/chris/ HTTP/1.1" 200 16289

29/7/1974
profile form is *NOT* valid
[23/Feb/2012 12:16:33] "POST /profile/chris/ HTTP/1.1" 200 16289

1974-07-29
profile form is *NOT* valid
[23/Feb/2012 12:18:15] "POST /profile/chris/ HTTP/1.1" 200 16289

这是我的模板

    <div class="input_area">
        <form id="profile_form" method="post" action="/profile/{{ user.username }}/">{% csrf_token %}
            {{ form.as_p }}
            <input type="submit" id="submit" value="save" class="submitButton idle" style="width:70px" />
        </form>
    </div>

这是我的观点.py

def profile(request, username):
    form = ProfileForm(request.POST)
    print request.POST.get('date_of_birth', 'None')
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        raise Http404(u'User not Found')
    if form.is_valid():
        print 'profile form is valid'
    else:
        print 'profile form is *NOT* valid'

最后这是我的 forms.py(暂时不要使用 clean_data 函数)

class ProfileForm(forms.Form):

    tz = []
    timezones = Timezone.objects.all()
    for timezone in timezones:
        val = str(timezone.hour)
        v = val.split(':')
        tuple = (timezone.id, '('+timezone.sign+''+v[0]+':'+v[1]+') '+timezone.name)
        tz.append(tuple)

    sex = [('male','male'),('female', 'female'),('unknown', 'prefer not to say')]
    real_name = forms.CharField(label=u'real name', widget=forms.TextInput, required=False)
    date_of_birth = forms.DateField(label=u'date of birth', input_formats='%d/%m/%Y', required=False, widget=forms.DateInput(format = '%d/%m/%Y'))
    pp_email = forms.EmailField(label=u'Paypal Email', widget=forms.TextInput, required=False)
    gender = forms.ChoiceField(label=u'sex', choices=sex, widget=forms.Select(), required=False)
    timezone = forms.ChoiceField(label=u'time zone', choices=tz, widget=forms.Select())
    address = forms.CharField(label=u'street address', widget=forms.Textarea, required=False)
    postal  = forms.CharField(label=u'postal code', widget=forms.TextInput, required=False)

【问题讨论】:

  • 你想输入什么日期?
  • 向我们展示输入。向我们展示您拥有的任何非字段表单代码。向我们展示相关的视图代码。
  • settings.TIME_ZONE = '欧洲/雅典'

标签: django django-forms datefield


【解决方案1】:

【讨论】:

  • 等等,这个问题是怎么解决的?我没有指定自定义输入格式,我有同样的问题,应该回退到默认值。日期仍然无效。
  • 对我有用。 date_of_birth = forms.DateField(label=u'date of birth', input_formats=['%d/%m/%Y', '%m/%d/%Y',], required=False, widget=forms.DateInput(format = '%d/%m/%Y'))
【解决方案2】:

使用 Django 1.6 及更高版本,您可以在表单的 Meta 中使用 localized_fields 或在表单中使用 localize=True。见https://docs.djangoproject.com/en/1.9/topics/i18n/formatting/#format-localization

当使用USE_L10N = True 时,Django 将为您的语言环境使用formats.py 文件(LANGUAGE_CODE 的一部分)。

你可以得到这样的 DRY(因为 models.py 中指定的 fields 不需要在 forms.py 中重复):

class SomeForm(forms.Form):

    class Meta:
        model = SomeModel
        fields = ('first_name', 'dob',)
        localized_fields = ('dob',)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 2012-09-08
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多