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 %}
    <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,注意结果的缓存问题

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 %}
    <h2>{{publisher.name}} Book List</h2>
    <ul>
        {% for book in books_list %}
            <li>{{ book.title }}</li>
        {% endfor %}
    </ul>
{% endblock %}

你可能感兴趣的:(html,django,UP,出版)