django通用视图
通用视图
1. 前言
2. 使用通用视图
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
url(r'^about/$', direct_to_template, {'template': 'about.html'}),
)

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from mysite.books.views import about_pages
urlpatterns = patterns('',
(r'^about/$', direct_to_template, {
'template': 'about.html'
}),
(r'^about/(\w+)/$', about_pages),
)
# view.py
from django.http import Http404
from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template
#由正则匹配的参数
def about_pages(request, page):
try:
return direct_to_template(request, template="about/%s.html" % page)#返回的HttpResponse
except TemplateDoesNotExist:
raise Http404()

安全问题的题外话

3. 用于显示对象内容的通用视图
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
#urls.py
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher
publisher_info = {
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
}
urlpatterns = patterns('',
url(r'^publishers/$', list_detail.object_list, publisher_info),
)
<h2>Publishers</h2>
<ul>
{% for publisher in object_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>

4. 通用视图的几种扩展用法
4.1 自定义结果集的模板名
'queryset': Publisher.objects.all(),
'template_name': 'publisher_list_page.html',
'template_object_name': 'publisher',
}
<ul>
{% for publisher in publisher_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
4.2 增加额外的context
'queryset': Publisher.objects.all(),
'template_object_name': 'publisher',
'template_name': 'publisher_list_page.html',
'extra_context': {'book_list': Book.objects.all()}
}
<ul>
{% for publisher in publisher_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
<h2>Book</h2>
<ul>
{% for book in book_list %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>

return Book.objects.all()
publisher_info = {
'queryset': Publisher.objects.all(),
'template_object_name': 'publisher',
'template_name': 'publisher_list_page.html',
'extra_context': {'book_list': get_books},
}
'queryset': Publisher.objects.all(),
'template_object_name': 'publisher',
'extra_context': {'book_list': Book.objects.all},
}
4.3 查看结果集的子集
'queryset': Book.objects.filter(publisher__name='Apress'),
'template_name': 'books/apress_list.html',
}
urlpatterns = patterns('',
url(r'^books/apress/$', list_detail.object_list, apress_books),
)
4.4 更灵活的结果集操作
urlpatterns = patterns('',
url(r'^publishers/$', list_detail.object_list, publisher_info),
url(r'^books/(\w+)/$', books_by_publisher),
)
#views.py
from django.shortcuts import get_object_or_404
from django.views.generic import list_detail
from mysite.books.models import Book, Publisher
def books_by_publisher(request, name):
# Look up the publisher (and raise a 404 if it can't be found).
publisher = get_object_or_404(Publisher, name__iexact=name)
# Use the object_list view for the heavy lifting.
return list_detail.object_list(
request,
queryset = Book.objects.filter(publisher=publisher),
template_name = 'books_by_publisher.html',
template_object_name = 'book',
extra_context = {'publisher': publisher}
)
4.5 利用通用视图做额外工作
from mysite.books.views import author_detail
urlpatterns = patterns('',
# ...
url(r'^authors/(?P<author_id>\d+)/$', author_detail),
# ...
)
#views.py
import datetime
from django.shortcuts import get_object_or_404
from django.views.generic import list_detail
from mysite.books.models import Author
def author_detail(request, author_id):
# 执行通用视图函数,但不立即返回HttpResponse对象
response = list_detail.object_list(
request,
queryset = Author.objects.all(),
object_id = author_id,
)
# 记录访问该作者的时间
now = datetime.datetime.now()
Author.objects.filter(id=author_id).update(last_accessed=now)
# 返回通用视图生成的HttpResponse对象
return response
response = list_detail.object_list(
request,
queryset = Author.objects.all(),
mimetype = 'text/plain',
template_name = 'author_list.txt'
)
#修改响应格式,使其的内容不直接显示在网页中,而是储存在文件中,下载下来。
response["Content-Disposition"] = "attachment; filename=authors.txt"
return response
<ul>
{% for author in object_list %}
<li>{{ author.first_name }}</li>
{% endfor %}
</ul>
运行结果为生成authors.txt文件并提供下载:

django通用视图的更多相关文章
- Django通用视图APIView和视图集ViewSet的介绍和使用
原 Django通用视图APIView和视图集ViewSet的介绍和使用 2018年10月21日 14:42:14 不睡觉假扮古尔丹 阅读数:630 1.APIView DRF框架的视图的基类是 ...
- Django通用视图执行过程
使用通用视图后,Django请求处理过程(以ListView为例):在我们自定义的视图中: class IndexView(ListView): template_name = 'blog/index ...
- django通用视图(类方法)
这周是我入职的第一周,入职第一天看到嘉兴大佬的项目代码.视图中有类方法,我感到很困惑. 联想到之前北京融360的电话面试,问我有无写过类方法……看来有必要了解下视图的类方法,上网搜了很多,原来这就是所 ...
- 6:django 通用视图
上一节我们介绍了django视图函数里面几个常用的函数,这节我们来看一下django为我们提供的一些通用视图吧 在最后面有我自己的示例代码,html部分太多了就不贴了 “简单”视图函数 正如名字所言, ...
- django通用视图之TemplateView和ListView简单介绍
django支持类视图,与此同时django为我们提供了许多非常好用的通用视图供我们使用,这其中TemplateView.ListView和DetailView是我们经常使用到的,这里就对Templa ...
- Django通用视图APIView和视图集ViewSet的介绍和使用(Django编程-1)
1.APIView DRF框架的视图的基类是 APIView APIView的基本使用和View类似 Django默认的View请求对象是 HttpRequest,REST framework 的请求 ...
- Django - 通用视图
urls.py from . import views ... url(r'^$', views.IndexView.as_view, name="index"), url(r'^ ...
- Django:之Sitemap站点地图、通用视图和上下文渲染器
Django中自带了sitemap框架,用来生成xml文件 Django sitemap演示: sitemap很重要,可以用来通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录. 开启si ...
- Django 1.6 基于类的通用视图
Django 1.6 基于类的通用视图 最初 django 的视图都是用函数实现的,后来开发出一些通用视图函数,以取代某些常见的重复性代码.通用视图就像是一些封装好的处理器,使用它们的时候只须要给出特 ...
随机推荐
- js 查找指定函数的内容
function test(){ //hahahhahahhahahha }alert(test.toString());
- iOS 自动编译脚本
#!/bin/sh #项目路径 PROJECT_DIR="/Users/mac/Desktop/_housemart" #临时项目 PROJECT_TEMP_DIR="/ ...
- jquery计算出left和top,让一个div水平垂直居中的简单实例
if($("#cont1").css("position")!="fixed"){ $("#cont1" ...
- CSS样式中” 大于号”
CSS样式中” 大于号” 在一段CSS代码中见到一个大于号(>),代码如下: BODY#css-zen-garden > DIV#extraDiv2 { BACKGROUND-IMAGE: ...
- C语言中文件目录(一正二反)斜杠
正斜杠unix“/” linux,安卓,苹果都是 windows是两个反斜杠“\\”,但现在也兼容了可以使用正斜杠“/”
- angularJs 页面{{xxx}}使用三目运算符
<td>{{::item.sex=='w'?'女':'男'}}</td>,记得引号.也可以不用::,用不用::的区别,自行百度
- [java] java 中Unsafe类学习
java不能直接访问操作系统底层,而是通过本地方法来访问.Unsafe类提供了硬件级别的原子操作,主要提供了以下功能: 1.通过Unsafe类可以分配内存,可以释放内存: 类中提供的3个本地方法all ...
- 【渗透测试学习平台】 web for pentester -6.命令执行
命令执行漏洞 windows支持: | ping 127.0.0.1|whoami || ping 2 || whoami (哪条名 ...
- C++类中的static数据成员,static成员函数
C++类中谈到static,我们可以在类中定义static成员,static成员函数!C++primer里面讲过:static成员它不像普通的数据成员,static数据成员独立于该类的任意对象而存在, ...
- cocos2d-x游戏引擎核心之三——主循环和定时器
一.游戏主循环 在介绍游戏基本概念的时候,我们曾介绍了场景.层.精灵等游戏元素,但我们却故意避开了另一个同样重要的概念,那就是游戏主循环,这是因为 Cocos2d 已经为我们隐藏了游戏主循环的实现.读 ...