Search code examples
pythondjangodjango-templatestime-formattimefield

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 not work (it gives me 'NoneType' object has no attribute 'strptime')


Solution

  • 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'))