Your problem is that you're not actually returning the converted values.
delivery_daterange = self.cleaned_data['delivery_daterange']
[...]
return delivery_daterange
That just returns the same string, unparsed. You could do something like this instead:
def clean_delivery_daterange(self):
[...]
delivery_from = datetime.datetime.strptime(str_delivery_from, "%d %b %Y")
delivery_to = datetime.datetime.strptime(str_delivery_to, "%d %b %Y")
return (delivery_from, delivery_to)
def clean_pickup_daterange(self):
[...]
pickup_from = datetime.datetime.strptime(str_pickup_from, "%d %b %Y")
pickp_to = datetime.datetime.strptime(str_pickup_to, "%d %b %Y")
return (pickup_from, pickup_to)
And then in the view:
new_obj.date_pickup_from, new_obj.date_pickup_to = form.cleaned_data['pickup_daterange']
An alternate approach would be to simply return the text values, then convert to Date
objects in your view:
def form_valid(self, form):
new_obj = form.save(commit=False)
pickup_start_string, pickup_end_string = form.cleaned_data['pickup_daterange'].split(' to ')
new_obj.date_pickup_from = strptime(pickup_start_string, "%d %b %Y")
#...etc
A more advanced approach would be to define a custom field to cover the concept of a date range, and define its to_python
method to return, say, a tuple of Date
objects.
Personally, I would simplify the whole thing and just let date_pickup_from
and the rest be DateField
instances in the form, maybe with a custom widget if I wanted to use something like a jQuery DatePicker to help the user pick the dates, and take care of special rendering in the template.