django系列8:优化vote页面,使用通用视图降低代码冗余
修改detail.html,将它变为一个可用的投票页面
<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>
修改views.py中vote的部分,和detail.html联合起来,记录票数,编辑对应的操作反馈
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question
# ...
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):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
里面用到了重定向,HttpResponseRedirect,重定向页面到 polls:results,传入的content是question.id,这里对投票完成页面的results的views做优化
from django.shortcuts import get_object_or_404, render
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
创建一个results.html,显示投票结果
<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 'polls:detail' question.id %}">Vote again?</a>
details和results的view 有很多代码相同之处,这里修改为使用通用视图,降低代码冗余
修改conf
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
修改views
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
... # same as above, no changes needed.
至此,教程结束。
剩余的测试代码部分,优化界面部分,打包和引用部分,已经执行过,但是篇幅太长,建议直接登录官网查阅文档。
https://docs.djangoproject.com/en/2.1/intro/tutorial06/
django系列8:优化vote页面,使用通用视图降低代码冗余的更多相关文章
- django系列7:修改404页面展示,优化模板,降低urlconf和模板之间的耦合,命名app将模板和app绑定
为了增加程序的友好和健壮性,修改view代码,处理以下如果出现404,页面的UI展示. 修改view代码 from django.http import Http404 from django.sho ...
- Django 1.10中文文档-第一个应用Part4-表单和通用视图
本教程接Part3开始.继续网页投票应用程序,并将重点介绍简单的表单处理和精简代码. 一个简单表单 更新一下在上一个教程中编写的投票详细页面的模板polls/detail.html,让它包含一个HTM ...
- django通用视图(类方法)
这周是我入职的第一周,入职第一天看到嘉兴大佬的项目代码.视图中有类方法,我感到很困惑. 联想到之前北京融360的电话面试,问我有无写过类方法……看来有必要了解下视图的类方法,上网搜了很多,原来这就是所 ...
- Django_通用视图(五)
参考官网的投票系统,按照综合案例的流程创建应用polls,主要模块代码如下: test1/polls/models.py import datetime from django.db import m ...
- 用基于类的通用视图处理表单(Class-based generic views)
处理表单通常包含3步: 初始化GET(空白的后者预填充的表单) POST非法数据(通常重新显示带有错误信息的表单) POST合法数据(提交数据并重定向) 为了将你从这些烦人的重复步骤中解救出来,Dja ...
- 基于类的通用视图(Class-based generic views)
在web开发中,最令人头痛的就是一遍又一遍的重复固定的模式.在解决了模板层面和模型层面的重复代码之痛之后,Django使用通用视图来解决视图层面的代码重复. 扩展通用视图 毫无疑问通用视图可以大幅度地 ...
- Django 系列博客(十四)
Django 系列博客(十四) 前言 本篇博客介绍在 html 中使用 ajax 与后台进行数据交互. 什么是 ajax ajax(Asynchronous Javascript And XML)翻译 ...
- 5 第一个Django第4部分(表单和通用视图)
上一节完成了视图编写,这一节为应用添加投票功能,也就是表单提交. 5.1编写一个简单的表单 5.2使用通用视图 5.3改良视图 5.1编写一个简单的表单 在网页设计中添加Form元素 polls/te ...
- Django 系列博客(二)
Django 系列博客(二) 前言 今天博客的内容为使用 Django 完成第一个 Django 页面,并进行一些简单页面的搭建和转跳. 命令行搭建 Django 项目 创建纯净虚拟环境 在上一篇博客 ...
随机推荐
- 瞧一瞧!这儿实现了MongoDB的增量备份与还原(含部署代码)
一 需求描述 我们知道数据是公司的重要资产,业务的系统化.信息化就是数字化.数据高效的存储与查询是系统完善和优化的方向,而数据库的稳定性.可靠性是实现的基础.高可用和RPO(RecoveryPoint ...
- Linux学习历程——Centos 7 touch命令
一.命令介绍 touch 命令用于创建空白文件,以及设置文件的时间. ----------------------------------------------------------------- ...
- IOS开发protocol使用
1.什么是protocol? protocol(协议)是用来定义对象的属性和行为,用于回调. 2.protocol分类? 协议中有三个修饰关键字@required和@optional和@propert ...
- win10 系统 wifi自动断开连接 wifi热点不稳定
我的系统的电脑是win10系统,笔记本 下载了一个wifi共享大师,但是wifi总是自动断,于是就找了找问题所在 在网上看了许多方案,大多数都是 在 电源管理 把[允许计算机关闭此设备以节 ...
- android菜鸟,了解android工程目录结构
- LOJ #2542. 「PKUWC 2018」随机游走(最值反演 + 树上期望dp + FMT)
写在这道题前面 : 网上的一些题解都不讲那个系数是怎么推得真的不良心 TAT (不是每个人都有那么厉害啊 , 我好菜啊) 而且 LOJ 过的代码千篇一律 ... 那个系数根本看不出来是什么啊 TAT ...
- hbase 迁库移库步骤
1 将数据导出 hbase org.apache.hadoop.hbase.mapreduce.Export t_zyzx_grzyfwtjxxb /hbase/data_backup/2018103 ...
- centos7下kubernetes(12。kubernetes-service)
Service:定义了一个服务得访问入口地址,前端的应用通过这个入口地址访问其背后得一组由pod副本组成的集群实例: service与后端的pod副本集群之间则是通过label selector来实现 ...
- 洛谷P1238 走迷宫题解
题目描述 有一个m*n格的迷宫(表示有m行.n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,文件读入这m*n个数据和起始点.结束点(起始点和结束点都是用两个数据来描述的,分别表示 ...
- Autoware(1)——快速开始
该部分可参照github Autoware中的 Demo Quick_Start. 1. 建立目录“.autoware”来保存demo数据 mkdir .autoware 2. 下载Demo数据下载d ...