用户通过复选框选择一个插槽,还应输入用户名,如下面的模板所示:
<form action="/clubs/{{ club.id }}/vote/" method="post">
{% csrf_token %}
{% for slot in tom_open_slots %}
<input type="checkbox" name="slot" id="slot{{ forloop.counter }}" value="{{ slot.id }}" />
<label for="slot{{ forloop.counter }}">{{ slot.slot }} on Court {{slot.court}}</label><br />
{% endfor %}
<input type="text" name="username" />
<input type="submit" value="Reserve" />
然后,我想在复选框中显示键入的用户名和时间。我通过以下视图和模板执行此操作:
def vote(request, club_id):
if 'username' in request.GET and request.GET['username'] and 'slot' in request.GET and request.GET['slot']:
username = request.GET['username']
slot = request.GET['slot']
return render_to_response('reserve/templates/vote.html',{'username':username, 'slot':slot})
else:
return HttpResponse('Please enter a username and select a time.')
{{slot}}
{{username}}
当我去vote.html时,我总是收到错误消息(请输入用户名并选择时间)。在未获取2 GET参数的视图中有什么不正确?
答案 0 :(得分:2)
您在表单中使用POST
请求:
<form action="/clubs/{{ club.id }}/vote/" method="post">
但是在视图中,您正在检查来自GET
请求的GET
对象:
request.GET
将表单方法更改为method="get"
以解决问题。
修改:点击此处GET
与POST
请求了解详情:When do you use POST and when do you use GET?
答案 1 :(得分:1)
在Django中,HttpRequest对象有三个字典,可以为您提供请求参数:
request.GET
为您提供查询字符串参数
request.POST
为您提供发布数据,
request.REQUEST
同时为您提供。
在您的情况下,由于表单使用的是POST
方法,因此您应使用request.POST
或request.REQUEST
。
仅供参考:https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET