Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set input to AM PM in django timefield

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?

like image 466
Atma Avatar asked Nov 04 '14 17:11

Atma


3 Answers

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

like image 98
virsunen Avatar answered Sep 19 '22 18:09

virsunen


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.

like image 42
smarlowucf Avatar answered Sep 23 '22 18:09

smarlowucf


I think you can do some thing like this in forms.py

field = DateTimeField(input_formats='%H:%M %p',...)
like image 28
Geo Jacob Avatar answered Sep 20 '22 18:09

Geo Jacob