Django笔记7(通用视图)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iteye_21297/article/details/81728444
[b]1. 一个呈现静态“关于”页面的URLconf[/b]

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
('^about/$', direct_to_template, {
'template': 'about.html'
})
)

注意:页面有中文,模板文件请使用UTF-8编码

[b]2. 在我们自己的视图中重用它[/b]

from django.conf.urls.defaults import
from django.views.generic.simple import direct_to_template
from mysite.views import *

urlpatterns = patterns('',
('^about/$', direct_to_template, {
'template': 'about.html'
}),
('^about/(\w+)/$', about_pages),
)


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)
except TemplateDoesNotExist:
raise Http404()


[b]3. 对象的通用视图[/b]

from django.views.generic import list_detail
from mysite.books.models import *
publisher_info = {
"queryset" : Publisher.objects.all(),
"template_object_name" : "publisher",
"template_name" : "books/publisher_list.html",
"extra_context" : {"book_list" : Book.objects.all()}
}
urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)

{% extends "base.html" %}

{% block content %}
<h2>Publishers</h2>
<ul>
{% for publisher in publisher_list %}
<li>{{ publisher.name }}</li>
{% endfor %}
</ul>
{% endblock %}

注意publisher_info各参数的默认值,template_object_name默认为object_list,template_name默认为books/publisher_list.html,注意结果的缓存问题

[b]4. 显示某个出版商的所有书籍[/b]

urlpatterns = patterns('',
(r'^publishers/$', list_detail.object_list, publisher_info),
(r'^books/(\w+)/$', books_by_publisher),
)

from django.views.generic import list_detail
from mysite.books.models import *
def books_by_publisher(request, name):

# Look up the publisher (and raise a 404 if it can't be found).
try:
publisher = Publisher.objects.get(name__iexact=name)
except Publisher.DoesNotExist:
raise Http404

# Use the object_list view for the heavy lifting.
return list_detail.object_list(
request,
queryset = Book.objects.filter(publisher=publisher),
template_name = "books/books_by_publisher.html",
template_object_name = "books",
extra_context = {"publisher" : publisher}
)

{% extends "base.html" %}

{% block content %}
<h2>{{publisher.name}} Book List</h2>
<ul>
{% for book in books_list %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% endblock %}
展开阅读全文

没有更多推荐了,返回首页