我正在尝试使这个简单的代码起作用:
class TestForm(forms.Form):
start_date = forms.DateField(widget=SelectDateWidget())
end_date = forms.DateField(widget=SelectDateWidget())
def test(request):
form = TestForm(request.GET)
if form.is_valid():
start = request.GET.get('start_date')
end = request.GET.get('end_date')
test_var = 'Hello'
return render(request, 'schedule/test.html', locals())
{% extends "base.html" %}
{% block content %}
<form method="get">
<table>
{{ form.as_table }}
<tr><td><input type="submit"></td><td></td></tr>
</table>
</form>
<br/>
<b>Start date</b>: {{ start }}<br />
<b>End date</b>: {{ end }}<br />
<b>Test var:</b> {{ test_var }}
{% endblock %}
看起来SelectDateWidget没有正确设置{{start}}和{{end}}变量:
我做错了什么?
答案 0 :(得分:3)
通过已清理的数据访问表单值,请尝试:
start = form.cleaned_data.get('start_date')
end = form.cleaned_data.get('end_date')
如果你想要它们按天,月和年传递的参数:
print:request.GET会给你:
<QueryDict: {u'end_date_day': [u'4'], u'start_date_day': [u'1'], u'end_date_year': [u'2012'], u'end_date_month': [u'3'], u'start_date_month': [u'2'], u'start_date_year': [u'2012']}>