我正在尝试提供一个表单,让用户选择日期范围以在Django中生成Web查询。我在查看过滤日期时遇到错误,我无法删除日期。
这是我的forms.py
:
class ReportFiltersForm(forms.Form):
start_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
end_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
我的观点
if request.method == 'POST':
form = ReportFiltersForm(request.POST)
sdy = request.POST['start_date_year']
sdm = request.POST['start_date_month']
sdd = request.POST['start_date_day']
edy = request.POST['end_date_year']
edm = request.POST['end_date_month']
edd = request.POST['end_date_day']
start_date= datetime.date(sdy, sdm, sdd)
end_date= datetime.date(edy, edm,edd)
回溯
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/projects/acms/cms/views.py", line 470, in eventreports
start_date= datetime.date(sdy, sdm, sdd)
TypeError: an integer is required
答案 0 :(得分:3)
你在这里犯了很多错误。
首先,为了修复您的TypeError
,您需要将数据投射到int
,如下所示:
...
sdy = int(request.POST['start_date_year'])
#Do the same with the other 5 fields
然而,这是一种非常糟糕的做事方式。首先,您必须在每个字段周围放置try/except
块以确保用户输入整数而不是字符串。
由于您已经在使用Django Forms,为什么不让它为您完成所有工作?您将如何执行此操作:
if request.method == 'POST':
form = ReportFiltersForm(request.POST)
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
#Do whatever you need to do with this data now. Since you had
#defined the fields as DateFields, you will automatically get
#datetime.date objects.
else:
return render_to_response('mytemplate.html', {'form' : form})
....
出于几个原因,这是一种更好的做事方式。使用这种方式,您可以让Django为您验证用户输入。此外,它还会将此数据转换为datetime.date
个对象。最后,如果用户输入了无效数据,它将允许您向用户提供更好的错误消息。