Pergunta

I have a daterangepicker from which the users set date. The choice of format is "DD MMM YYYY" now to go with that i'm using

    datetime.datetime.strptime(time, "%d %b %Y");

but still i am getting an error

    Exception Value:[u"'01 Aug 2013' value has an invalid date format. It must be in   YYYY-MM-DD format."]

any idea what might be going wrong? stuck on this for a while.

    def form_valid(self, form):
      new_obj = form.save(commit=False)
      new_obj.date_pickup_from, new_obj.date_pickup_to = form.cleaned_data['pickup_daterange'].split(' to ')
      new_obj.date_delivery_from, new_obj.date_delivery_to = form.cleaned_data['delivery_daterange'].split(' to ')

here are the forms

pickup_daterange = forms.CharField(
    label=_('Pickup Within'),
    widget=forms.TextInput(attrs={'class': 'daterange'}),
    validators=[
        RegexValidator(
            regex=r'\d{2}\ \w{3}\ \d{4}\ to\ \d{2}\ \w{3}\ \d{4}',
            message=_(u'Range must be of format "mm/dd/yyyy to mm/dd/yyyy"'),
            code='invalid_range'
        )
    ],
    help_text=_('Within what dates do you want the pickup?')
)
delivery_daterange = forms.CharField(
    label=_('Delivery Within'),
    widget=forms.TextInput(attrs={'class': 'daterange'}),
    validators=[
        RegexValidator(
            regex=r'\d{2}\ \w{3}\ \d{4}\ to\ \d{2}\ \w{3}\ \d{4}',
            message=_(u'Range must be of format "mm/dd/yyyy to mm/dd/yyyy"'),
            code='invalid_range'
        )
    ],
    help_text=_('Within what dates do you want the delivery?')
)

models.py

date_delivery_from = models.DateField(_('Date of Delivery From'), blank=True, null=True)
date_delivery_to = models.DateField(_('Date of Delivery To'), blank=True, null=True)

function in my form class from where i am calling strptime

    def clean_delivery_daterange(self):
      daterange_pattern = re.compile(r'(\d{2}\ \w{3}\ \d{4})\ to\ (\d{2}\ \w{3}\ \d{4})')
      delivery_daterange = self.cleaned_data['delivery_daterange']
      pickup_daterange = self.cleaned_data['pickup_daterange']

      str_pickup_from, str_pickup_to = daterange_pattern.search(pickup_daterange).groups()
      str_delivery_from, str_delivery_to = daterange_pattern.search(delivery_daterange).groups()

      delivery_from = datetime.datetime.strptime(str_delivery_from, "%d %b %Y")
      pickup_from = datetime.datetime.strptime(str_pickup_from, "%d %b %Y")
      if delivery_from < pickup_from:
        raise forms.ValidationError('Delivery dates cannot be before pickup dates')
      return delivery_daterange
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top