Django Forms: TimeField Validation
Asked Answered
U

2

10

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?

Underpass answered 26/5, 2010 at 14:11 Comment(1)
You won't be able to use %P like that, I'm fairly certain that is just for output, and can't be used for parsing (i.e. as an input mask). What ValidationError do you get exactly?Murmuration
M
11

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.

Mag answered 26/5, 2010 at 18:27 Comment(0)
U
13

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.)

Underpass answered 26/5, 2010 at 16:7 Comment(2)
Thanks, for Django 1.5 use TIME_INPUT_FORMATS = ['%H:%M', '%I:%M%p', '%I:%M %p']Hocker
Also note that %p doesn't allow A.M. or P.M.Hintze
M
11

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.

Mag answered 26/5, 2010 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.