Django接受AM/PM作为表单输入 [英] Django Accepting AM/PM As Form Input

查看:55
本文介绍了Django接受AM/PM作为表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用DateTime字段在Django中接受am/pm作为时间格式,但是遇到了一些麻烦.我试图在我的forms.py文件中设置像这样

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"])

具有以下数据:

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.

我还尝试按照文档说明在settings.py中设置全局变量:

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

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

什么是有效的,如果我在没有am/pm的情况下提交数据,但输出为

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

还有其他选择吗?

推荐答案

DATETIME_INPUT_FORMATS不适用于包含%p 的格式. input_formats kwarg都不会.

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

作为快速解决方法,您可以在 Form __ init __ DateTimeField input_formats 属性>方法.例如:

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文档说%p不能用于解析日期字段.

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

但是,如果您浏览源代码,DateTimeField的to_python方法并没有真正执行类似的操作.

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

这篇关于Django接受AM/PM作为表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆