Reputation: 872
I'm having a problem saving a datetime object from a form. The form widget gives me a text string like this: 2012-09-20 04:41 PM
I'm trying to override the clean method in the form, like this:
class LegForm(ModelForm):
formfield_callback = make_custom_field
class Meta:
model = Leg
exclude = ('riders', 'drivers', 'open_to_prefs','carpool')
widgets = { 'days': forms.CheckboxSelectMultiple }
def clean_drive_date_time(self):
twelve_hour = self.cleaned_data['drive_date_time']
print "drive time: " + str(twelve_hour)
data = datetime.strptime(twelve_hour, "%Y-%m-%d %I:%M %p")
print "24 hour drive time: " + str(data)
return data
the strptime statement works from the command line and gives me a valid datetime object, but when I try it in the project as shown above, I get an error on my form telling me " Enter a valid date/time."
I can save the datetime no problem without a override of the clean method if I use 24 hour format, but that's more difficult for the end user. Any help is appreciated. Thanks!
Upvotes: 1
Views: 1733
Reputation: 27861
The job of the form field is to take an input from the user and normalize it to a python value. A python's datetime object does not care if its 12/24 hour formats. All it stores is a datetime in some universal way, which you can represent in either 12/24 formats.
So from what I understand you are trying to do is to get input from users in 24 hour hour, instead of 12 hour format. The easiest way is to tell the django form field the format you expect from users and it will automatically convert the string from the user to a python datetime object.
class LegForm(ModelForm):
formfield_callback = make_custom_field
# overwrite the default DateTimeField with defaults parameters
drive_date_time = DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'])
class Meta:
model = Leg
exclude = ('riders', 'drivers', 'open_to_prefs','carpool')
widgets = { 'days': forms.CheckboxSelectMultiple }
Upvotes: 3