程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

django_视图相关

发布于2019-08-06 09:54     阅读(754)     评论(0)     点赞(2)     收藏(0)


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

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.pythonheidong.com/blog/article/7265/c9d5edbe98fc2e77bf14/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

2 0
收藏该文
已收藏

评论内容:(最多支持255个字符)