zoukankan      html  css  js  c++  java
  • 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}
    )

     

  • 相关阅读:
    js用currentStyle和getComputedStyle获取css样式(非行间)
    XMLHttpRequest Level 2 使用指南
    image-set实现Retina屏幕下图片显示[转载]
    Png的秘密
    css清除&闭合浮动
    2016学习计划
    提高性能及操作硬件的能力
    新兵易学,老兵易用----C++(C++11的学习整理---如何减少代码量,加强代码的可读性)
    CV限制符--C++
    能ping通网络,也正常连接,就是打不开网页,无法访问网络
  • 原文地址:https://www.cnblogs.com/snow-l/p/11239402.html
Copyright © 2011-2022 走看看