Django Accepting AM/PM As Form Input

十年热恋 提交于 2021-01-27 12:43:33

问题


I am trying to figure out how to accept am/pm as a time format in Django using a DateTime field, but I am having some trouble. I have tried setting it like this in my forms.py file

pickup_date_time_from = DateTimeField(input_formats=["%m/%d/%Y %I:%M %p"])

with the following data:

12/31/2017 02:40 pm

However, I get a validation error when submitting the form:

(Hidden field pickup_date_time_from) Enter a valid date/time.

I have also tried setting a global variable in settings.py as the documentation states:

DATETIME_INPUT_FORMATS = ['%m/%d/%y %I:%M %p']

What does work is if I submit the data without the am/pm, but the output is

2017-12-31 02:40:00+00:00

Any other options?


回答1:


DATETIME_INPUT_FORMATS doesn't work for formats containg %p. Neither do input_formats kwarg.

As a quick work around, you can alter the input_formats attribute of DateTimeField in the Form's __init__ method. For example:

class DateTimeForm(forms.Form):
    CUSTOM_FORMAT = '%m/%d/%y %I:%M %p'

    date_input = forms.DateTimeField(widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.CUSTOM_FORMAT not in self.fields['date_input'].input_formats:
            self.fields['date_input'].input_formats.append(self.CUSTOM_FORMAT)

Django documentation does say that %p cannot be used in parsing date fields.

But if you go through the source code, the to_python method of DateTimeField doesn't really enforce anything like that.



来源:https://stackoverflow.com/questions/48046121/django-accepting-am-pm-as-form-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!