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 的视图都是用函数实现的,后来开发出一些通用视图函数,以取代某些常见的重复性代码.通用视图就像是一些封装好的处理器,使用它们的时候只须要给出特 ...
随机推荐
- 【Java集合的详细研究2】浅谈Arrays.asList的使用
首先,该方法是将数组转化为list.有以下几点需要注意: (1)该方法不适用于基本数据类型(byte,short,int,long,float,double,boolean) (2)该方法将数组与列表 ...
- solr 5.2.1 tomcat 7 配置过程笔记
因为这个是新版,网上很少这个配置文档,看网上其他的教程弄了很多次,都没有成功,幸亏有这个链接的文档, 才迅速的配置成功,其实是比以前简洁了.因为我的在 linux 上面安装,不方便截图,直接复制修改了 ...
- Unity的Asset Store商店下载文件路径
如果之前在Asset Store商店下载过资源包,结果下次用的时候找不到了,不用急,其实Unity把它自动保到下面这个目录了,最后一个文件夹名与版本号有关,找到前面的即可. C:\Users\Admi ...
- Makefile--基本规则(零)
[版权声明:转载请保留出处:周学伟:http://www.cnblogs.com/zxouxuewei/] 一般一个稍大的linux项目会有很多个源文件组成,最终的可执行程序也是由这许多个源文件编译链 ...
- simple fix 主从不一致滴error
Last_SQL_Error: Error 'Unknown table 'bb'' on query. Default database: 'test'. Query: 'DROP TABLE `b ...
- 【Java nio】Blocking nio2
package com.slp.nio; import org.junit.Test; import java.io.File; import java.io.IOException; import ...
- webpack----entry
入口文件下对象的键值,不多说,上图: 其实app就等同于name,于是乎 dist下的index.html中引入的js,就是: <script type="text/javascrip ...
- Mysql explain执行计划
EXPLAIN(小写explain)显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句. EXPLAIN + sql语句可以查看mysql的执行 ...
- 使用SSH工具连接到MySQL
在SSH中查看MySQL数据信息 格式为:mysql -h主机地址 -u用户名 -p用户密码 -P端口号 -D数据库名称 例如: mysql -uroot -p123456 -h192.168.1.1 ...
- Python 3 利用 Dlib 实现人脸 68个 特征点的标定
0. 引言 利用 Dlib 官方训练好的模型 “shape_predictor_68_face_landmarks.dat” 进行 68 个点标定: 利用 OpenCv 进行图像化处理,在人脸上画出 ...