Django表单:TimeField验证 [英] Django Forms: TimeField Validation

查看:149
本文介绍了Django表单:TimeField验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我在这里缺少一些明显的东西。我有一个Django表单,其中包含一个 TimeField 。我想要允许像10:30 AM这样的时间,但是我无法接受这种输入格式或使用%P格式(它具有一个附注说这是一个专有扩展名,但不说来自哪里。以下是我的表单代码的要点:

  calendar_widget = forms.widgets.DateInput(attrs = {'class':'date-选择'},format ='%m /%d /%Y')
time_widget = forms.widgets.TimeInput(attrs = {'class':'time-pick'})
valid_time_formats = [ '%P','%H:%M%A','%H:%M%A','%H:%M%a','%H:%M%a']

class EventForm(forms.ModelForm):
start_date = forms.DateField(widget = calendar_widget)
start_time = forms.TimeField(required = False,widget = time_widget,help_text ='ex:10: 30AM',input_formats = valid_time_formats)
end_date = forms.DateField(required = False,widget = calendar_widget)
end_time = forms.TimeField(required = False,widget = time_widget,help_text ='ex:10: 30AM',input_formats = valid_time_formats)
description = forms.CharField(widget = forms.Textarea)

任何时候我提交10:30 AM,我得到验证错误。底层模型有两个字段,event_start和event_end,没有时间字段,所以我不认为问题在那里。我错过了什么愚蠢的事情?

解决方案

您需要使用%I来解析指定%p的时间。请参阅这里的指令表中的第一个注释: http://docs.python。 org / library / time.html#time.strftime


I feel like I'm missing something obvious here. I have a Django form with a TimeField on it. I want to be able to allow times like "10:30AM", but I cannot get it to accept that input format or to use the "%P" format (which has a note attached saying it's a "Proprietary extension", but doesn't say where it comes from). Here's the gist of my form code:

calendar_widget = forms.widgets.DateInput(attrs={'class': 'date-pick'}, format='%m/%d/%Y')
time_widget = forms.widgets.TimeInput(attrs={'class': 'time-pick'})
valid_time_formats = ['%P', '%H:%M%A', '%H:%M %A', '%H:%M%a', '%H:%M %a']

class EventForm(forms.ModelForm):
    start_date = forms.DateField(widget=calendar_widget)
    start_time = forms.TimeField(required=False, widget=time_widget, help_text='ex: 10:30AM', input_formats=valid_time_formats)
    end_date = forms.DateField(required=False, widget=calendar_widget)
    end_time = forms.TimeField(required=False, widget=time_widget, help_text='ex: 10:30AM', input_formats=valid_time_formats)
    description = forms.CharField(widget=forms.Textarea)

Any time I submit "10:30AM", I get a validation error. The underlying model has two fields, event_start and event_end, no time fields, so I don't think the problem is in there. What stupid thing am I missing?

解决方案

You need to use %I to parse the hours when you specify %p. See the first note under the table of directives here: http://docs.python.org/library/time.html#time.strftime.

这篇关于Django表单:TimeField验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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