Django笔记7(通用视图)

本文介绍Django框架中的URL配置及视图应用案例,包括静态页面展示、对象列表视图、以及特定对象详情页的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[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 %}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值