开发者

TimeField format in Django template

I'm writing an application in Django and using several TimeFields in a model. I only want to work with the time format hh:mm (not hh:mm:ss or hh p.m./a.m. or other things). I have set the django setting TIME_FORMAT = 'H:i' and USE_L10N = False according to the documentation,

USE_L10N overrides TIME_FORMAT if set to True

In my template I'm using input boxes automatically created by Django like:

{{formName.timeField}}

The problem is that as long as I introduce something like "10:00" and do a POST, when the POST is done Django (or whatever) turns it into "10:00:00" (so it adds the seconds).

  • Is there a way to specify the format in which datetime fields display saved dates? If I could just use something like |date:"H:i" in the value of the input box that would do the trick.

On the other side I know I could do the input box manually (not directly using {{formName.timeField}}), but I've had some problems in the past with that so I would like to avoid that (at least for the moment).

There is also this similar question in Django TimeField Model without seconds, but the solution does n开发者_开发技巧ot work (it gives me 'NoneType' object has no attribute 'strptime')


I had exactly this problem in my app, and solved it by passing a format parameter to Django's TimeInput widget:

from django import forms

class SettingsForm(forms.Form):
    delivery_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M'))


Assuming you have a format you want all TimeFields to use, you can add the TIME_INPUT_FORMATS to your settings file. For example, TIME_INPUT_FORMATS = ('%I:%M %p',) will format your times as "5:30 PM".

The docs: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TIME_INPUT_FORMATS

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜