处理用户投票,问题详情页展示选项,用户选择之后点击投票
# appname/views.pyfrom django.http import HttpResponseRedirect # 跳转from django.shortcuts import render, get_object_or_404from django.urls import reverse # 不用硬编码,可以直接用 命名空间:页面名称 来生成链接from django.db.models import F # 避免竞争条件from .models import Question, Choicedef vote(request, question_id):"""处理用户投票"""question = get_object_or_404(Question, id=question_id)try:selected_choice = question.choice_set.get(pk=request.POST['choice'])# 如果 request.POST['choice'] 中没有数据就会引发 KeyErrorexcept (KeyError, Choice.DoesNotExist):# 重新加载投票表单return render(request, 'polls/detail.html', {'question': question,'error_message': '你没有选择任何选项'})else:# 增删数据用 Django 数据库 APIselected_choice.votes = F('votes') + 1 # 使用 F() 避免竞争条件selected_choice.save()# 处理好 POST 表单之后总要返回一个 HttpResponseRedirect# 防止用户后退导致表单提交两次# HttpResponseRedirect 只接收一个参数:重定向 URL# reverse('URLconf视图名', args=[URL 中所需参数])return HttpResponseRedirect(reverse('firstapp:result', args=[question.id]))
