当前位置: 移动技术网 > IT编程>脚本编程>Python > django_视图相关

django_视图相关

2019年07月25日  | 移动技术网IT编程  | 我要评论

千纤草官网,yy小说下载,天下女人心150

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

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

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网