-1

我有一个 daterangepicker,用户可以从中设置日期。格式的选择是“DD MMM YYYY”现在我正在使用

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

但我仍然遇到错误

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

知道可能出了什么问题吗?坚持了一段时间。

    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 ')

这是表格

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?')
)

模型.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)

在我调用 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
4

1 回答 1

1

您的问题是您实际上并没有返回转换后的值。

delivery_daterange = self.cleaned_data['delivery_daterange']
[...]
return delivery_daterange

那只是返回相同的字符串,未解析。你可以这样做:

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)

然后在视图中:

new_obj.date_pickup_from, new_obj.date_pickup_to = form.cleaned_data['pickup_daterange']

另一种方法是简单地返回文本值,然后Date在您的视图中转换为对象:

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

更高级的方法是定义一个自定义字段来涵盖日期范围的概念,并定义它的to_python方法来返回一个Date对象元组。

就个人而言,我会简化整个事情,只是让date_pickup_from其余的成为DateField表单中的实例,如果我想使用 jQuery DatePicker 之类的东西来帮助用户选择日期并处理特殊渲染,可能会使用自定义小部件模板。

于 2013-08-01T05:53:09.910 回答