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?
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
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.
I think you can do some thing like this in forms.py
field = DateTimeField(input_formats='%H:%M %p',...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With