django_视图相关

使用通用视图(返回静态页面)

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

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

无法捕捉没有该模板的错误,支持重写

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

对象的通用视图


帮助你很容易 地生成对象的列表和明细视图,当然还需要编写一个模板。 我们可以通过在额外参数字典中包含一个template_name键来显式地告诉object_list视图使用哪个模板

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('',
(r'^publishers/$', list_detail.object_list, publisher_info)
)

更改变量名

from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher

# 添加额外的Context
# 在模板中,通用视图会通过在template_object_name后追加一个_list的方式来创建一个表示列表项目的变量名。

publisher_info = {
'queryset': Publisher.objects.all(),
'template_object_name': 'publisher',
'extra_context': {'book_list': Book.objects.all}
}

urlpatterns=patterns('',(r'^publishers/$',list_detail.object_list,publisher_info))


用函数包装来处理复杂的数据过滤

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/books_by_publisher.html',
template_object_name = 'book',
extra_context = {'publisher': publisher}
)

 

原文地址:https://www.cnblogs.com/snow-l/p/11239402.html