strptime验证错误django

时间:2013-08-01 04:39:48

标签: python django strptime

我有一个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?')
)

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)

在我的表格类中起作用,我称之为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

1 个答案:

答案 0 :(得分: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

更高级的方法是定义custom field以涵盖日期范围的概念,并定义其to_python方法以返回(例如)Date个对象的元组。

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