表单
用来接收用户提交的投票选择。需要在前端显示一个让用户投票的页面。重写detail.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>
</body>
</html>
模板会显示一系列的单选按钮,按钮的值就是按钮的id,按钮的名字是字符串“choice”。当选择某个按钮时,会有一个包含数据chrice=#的post请求发送到指定url,#是被选择的选项id
form标签,action表示发送目的的url,method表示提交数据的方式
当发送post请求时,需要考虑跨站请求伪造的安全问题,简称CSRF。Django提供了一个简单的方法避免。在form表单添加{% csrf_token %}标签。但是如果是用ajax方式提交。就不能这样使用了。
增加视图和视图函数
在urls.py增加以下代码
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('polls/<int:question_id>/', views.detail, name='detail'),
path('polls/<int:question_id>/results/', views.results, name='results'),
path('polls/<int:question_id>/vote/', views.vote, name='vote'),
]
在views.py增加以下代码
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return render(request, 'results.html', {"question": question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'results.html', {'question': question})
vote用来处理投票表单
request.POST是一个类似字段的对象,允许使用键名来访问提交过来的数据。requests.POST[''choice]返回的就是选择项的id
当choice没有,捕获错误处理,否则choice投票结果+1

当有人对某个问题投票成功,显示投票结果页面,resulets用来显示投票结果
新增一个results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'detail' question.id %}">Vote again?</a>
</body>
</html>


764

被折叠的 条评论
为什么被折叠?



