set input to AM PM in django timefield

Atma picture Atma · Nov 4, 2014 · Viewed 9.7k times · Source

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?

Answer

virsunen picture virsunen · Jun 14, 2017

I was searching for a similar answer and I didn't find a suitable one for models.TimeField, so, the easiest solution that I found for doing this site wide would be to setting in your settings.py the following global variable:

TIME_INPUT_FORMATS = ['%I:%M %p',]

I hope this helps someone.

To use other formats see:

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior