Django generic view

1、ListView:

只需要在views.py文档中引用此类,即可很快生成template所需的list:

from django.views.generic import ListView
from books.models import Publisher

class PublisherList(ListView):
    model = Publisher #简洁!不需要任何额外的get方法
然后,即可对template/books/publisher_list.html进行简单渲染:

{% block content %}
    <h2>Publishers</h2>
    <ul>
        {% for publisher in object_list %} #或者:publiser_list(默认生成,model名称与list用下划线连接),该名字可以自己在view函数中指定:context_object_name = 'my_special_apply',然后用my_special_apply替换掉object_list即可
            <li>{{ publisher.name }}</li>
        {% endfor %}
    </ul>
{% endblock %}

而若想展示指定的数据(即先作筛选),则只需修改PublisherList类:

class PublisherList(ListView):
    queryset = Publisher.objects.filter(筛选条件) #简洁!甚至不需要指定model

很明显上面的写法中筛选条件不能做到动态进行,而只能写死,要做到动态,只需override ListView中的get_queryset(self)方法:

class PublisherList(ListView):
    # model = ApplyInfo #无需指定model

    def get_queryset(self):
        pub_name = self.request.GET.get("publisher_name", "")
        # addr = "上海"
        return Publisher.objects.filter(publisher_name=pub_name)
然后配合下面的函数来丰富context的内容

def get_context_data(self, **kwargs):

        context = super(Publisher, self).get_context_data(**kwargs)
        context['title'] = "demosd" #可加入更多额外的信息来丰富context
        return context

2、DetailView

当ListView提供的内容不足以用来展示时,我们需要其它更具体的信息,此时可用DetailView:

from django.views.generic import DetailView
from books.models import Publisher, Book

class PublisherDetail(DetailView):

    model = Publisher

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context
这样,context对象又多了一个key为book_list的数据。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值