Django表单:TimeField验证 [英] Django Forms: TimeField Validation
问题描述
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屋!