Django Forms: TimeField Validation

余生颓废 提交于 2019-12-04 19:25:43

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2913700/django-forms-timefield-validation

工具导航Map

JSON相关