Django笔记7(通用视图)

1. 一个呈现静态“关于”页面的URLconf

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编码
2. 在我们自己的视图中重用它

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()


3. 对象的通用视图

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 %}

Publishers

  • {% for publisher in publisher_list %}
  • {{ publisher.name }} {% endfor %}
{% endblock %}

注意publisher_info各参数的默认值,template_object_name默认为object_list,template_name默认为books/publisher_list.html,注意结果的缓存问题
4. 显示某个出版商的所有书籍

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 %}

{{publisher.name}} Book List

  • {% for book in books_list %}
  • {{ book.title }} {% endfor %}
{% endblock %}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值