【发布时间】:2014-06-19 05:18:48
【问题描述】:
在我当前基于 python 和 django 的应用程序中,我为日期创建了一个自定义小部件。
from datetime import date
from django.forms import widgets
class DateSelectorWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
# create choices for months, years
# example below, the rest snipped for brevity.
years = [(year, year) for year in range(1945, 2016)]
months = [(1,'Jan'),(2,'Feb')]
_widgets = (
widgets.Select(attrs=attrs, choices=months),
widgets.Select(attrs=attrs, choices=years),
)
super(DateSelectorWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
if value:
return [value.month, value.year]
return [None, None]
def format_output(self, rendered_widgets):
return u''.join(rendered_widgets)
def value_from_datadict(self, data, files, name):
datelist = [
widget.value_from_datadict(data, files, name + '_%s' % i)
for i, widget in enumerate(self.widgets)]
try:
D = date(day=1, month=int(datelist[0]),
year=int(datelist[1]))
except ValueError:
return ''
else:
return str(D)
在加载表单时它工作正常(返回日期对象),但是当我提交表单并将表单中的某些字段留为空时,我收到以下错误。
Caught AttributeError while rendering: 'str' object has no attribute 'month'
Request Method: POST
Request URL:
Django Version: 1.3.1
Exception Type: TemplateSyntaxError
Exception Value:
Caught AttributeError while rendering: 'str' object has no attribute 'month'
Exception Location: /var/www/stacks/django-apps/kkk/apps/oooomonth_year.py in decompress, line 21
【问题讨论】: