开发者

Django Forms: TimeField Validation

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)
 开发者_如何学Python   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?


Got it thanks to Karen's answer: the formatting characters aren't the ones listed for Django's now/ date filters, they're the ones for Python's time.strftime(format[, t]). To accept AM/ PM, you need to switch from %H to %I so the filters now look like:

valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']

(This message brought to you by open source code. Without it, I'd never have figured it out.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜