且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在django时域中将输入设置为AM PM

更新时间:2023-02-26 19:14:50

要获得12小时时间格式,您将使用以下内容:



输入(这是格式列表Django用于验证):

  field = TimeField(input_formats =('%I:%M%p',... ,...))

输出(这是Django将用于显示时间值的格式) :

  field = TimeField(widget = TimeInput(format ='%I:%M%p'))
%I表示12小时时钟格式,而%H表示24小时时钟格式。

b
$ b

此外,input_formats的默认列表可以在每个语言环境formats.py文件中找到。 Django将input_formats列表中的第一个格式用作时间字段的默认输出格式。


i want to allow users to be able to choose between am and pm with my django timefield

Currently if I enter:

11:00 AM

, i get a form error: "Enter a valid time."

If I enter:

11:00

the form validates with no problem.

I also tried:

class RemindersForm(forms.ModelForm):

    remdinder = forms.TimeField(input_formats='%H:%M %p',)

    class Meta:
        model = NotificationPreference
        fields = (
                  'reminder', 
                  )

This changes the input format to:

11:00:00

and still gives me the above validation error.

What am I doing wrong?

To get a 12hr time format you would use the following:

For input (This is the list of formats Django uses in validation):

field = TimeField(input_formats=('%I:%M %p',...,...))

For output (This is the format Django will use to display time values):

field = TimeField(widget=TimeInput(format='%I:%M %p'))

The %I indicates a 12 hour clock format whereas the %H indicates a 24 hour clock format.

Additionally, the default list of input_formats can be found in each locales formats.py file. Django uses the first format in the input_formats list as the default output format for time fields.