本教程从随笔三停止的地方开始. 这里将重点放简单的表单处理和削减我们的代码.
写一个简单的表单
更新模版文件 polls/detail.html, 以便包含一个 html<form> 元素:
- <body>
- <h1>{{ question.question_text }}</h1>
- {% if error_message %}<p><strong>{{ error_message }}</strong>></p>>{% endif %}
- <form action="{% url'polls: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>
说明:
上面的模版为每个问题选项显示一个单选按钮. value 按钮相关联的是问题的选择的 ID.name 为每个单选按钮的 choice. 这意味着, 当有人选择其中一个单选按钮并提交表单时, 它将发送 post 数据 choice=#,# 表示所选选项的 id.
forloop.counter 表示 for 标签经过其循环的次数
由于我们正在创建 POST 表单 (可能会影响其循环的次数). 简而言之, 所有以内部 URL 为目标的 POST 表单都应使用模版标记:{% csrf_token %}
表单写完, 就创建一个处理提交数据的 django 视图. 并对其进行处理.
打开 polls/views.py 文件编写代码:
- from django.urls import reverse
- 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,'polls/detail',{
- 'question':question,
- 'error_message':"You didn't select a choice.",
- })
- else:
- selected_choice.votes+=1
- selected_choice.save()
- return HttpResponse(reverse('polls:results',args=(question_id)))
这段代码包含本教程尚未涉及的一些内容:
request.POST 是一个类似字典的对象, 可以通过 key 访问提交的数据. request.POST['choice'] 以字符串形式返回所选项的 ID.
如果 request.POST['choice'] KeyError, 在 POST 数据中没有提供. 将会引发 error. 上面的代码会检查并重新显示问题并显示错误消息. You didn't select a choice.
增加了一个票数选择计数, 代码将返回一个 HttpResponseRedirect. 而不是一个正常的 response.HttpResponseRedirect 只有一个参数: 用户将被重定向到 URL.
reverse() 调用将返回一个类似的字符串:'/polls/3/results/'. 这个将重定向的 URL 会调用'results'视图显示最终结果.
当人在问题中投票后, 该 vote() 视图将到 results 页面. 我们来写下这个观点:
- polls/views.py:
- def results(request,question_id):
- question=get_object_or_404(Question,pk=question_id)
- return render(request,'polls/results.html',{'question':question})
可以看出, 这和 detail 视图几乎一样. 等下解决此冗余.
再去模版目录下创建: polls/results.html
- <body>
- <h1>{{ question.question_text }}</h1>
- <ul>
- {% for choice in question.choice_set.all %}
- <li>
- {{ choice.choice_text }} -- {{ choice.votes }}
票
- </li>
- {% endfor %}
- </ul>
- <a href="{% url'polls:detail'question.id %}"> 继续投票?</a>
- </body>
- </html>
现在, 可以进行投票了. 输入 127.0.0.1/polls 然后一直点击下去.
使用通用视图
之前有提到两个视图代码几乎一样. 冗余的, django 提供了一个称为'通用视图'系统的快捷方式.
将会:
转换 URLconf
删除一些旧的不需要的视图
基于 django 的通用视图引入新的视图
修改 URL 配置
首先打开 polls/urls.py 更改代码:
来源: https://www.cnblogs.com/xjmlove/p/9141515.html