【问题标题】:Switching to class-based list_detail切换到基于类的 list_detail
【发布时间】:2012-12-12 11:47:55
【问题描述】:

我的 IDE (PyCharm) 不断报告:基于函数的通用视图已被弃用。

我的导入列表中有以下语句:

from django.views.generic.list_detail import object_list

我的视图如下所示:

def category(request, id, slug=None):
    category = Category.objects.get(pk=id)

    books = Book.objects.filter(
        Q(status = 1) & Q(category=category)
    ).order_by('-id')

    s = Poet.objects.order_by('?')[:3]

    return object_list(
        request,
        template_name = 'books/categories/show.html',
        queryset = books,
        paginate_by = 99,
        extra_context = {
            'category': category,
            'suggestions': s,
            'bucket_name': config.BOOKS_BUCKET_NAME,
            }
    )

我在 SO 中找到了 this,但在这方面文档似乎过于复杂。

任何关于如何转换我的代码的提示都将不胜感激。

【问题讨论】:

    标签: python django


    【解决方案1】:

    你可以试试这样的

    from django.views.generic import ListView
    
    class CategoryView(ListView):
        template_name = 'books/categories/show.html'
        paginate_by = 99
    
        def get_queryset(self):
            self.category = Category.objects.get(pk=self.kwargs['id'])
    
            books = Book.objects.filter(
               Q(status = 1) & Q(category=self.category)
            ).order_by('-id')
    
            self.s = Poet.objects.order_by('?')[:3]
    
            return books
    
        def get_context_data(self, **kwargs):
            context = super(CategoryView, self).get_context_data(**kwargs)
            context['category'] = self.category
            context['suggestions'] = self.s
            return context
    

    此代码未经测试,如果它适合您,请报告。 请注意,书单将通过上下文变量“object_list”获得,如果您想给它一个不同的名称,可以使用“context_object_name”类成员:

    class CategoryView(ListView):
        template_name = 'books/categories/show.html'
        context_object_name = 'books'
        ...
    

    在你的 urls.py 中使用基于类的视图的 as_view() 方法

    url( r'your pattern', CategoryView.as_view(), name='whatever')
    

    【讨论】:

    • 谢谢,除了我有一个自定义分页之外几乎可以工作:{% if is_paginated %}{% load paginator %}{% paginator 3 %}{% endif %}... 和 paginator.py自定义模板标签我有 def paginator(context,similar_pages=2,is_random=False): 这个函数的第一行是 startPage = max(context['page'] -similar_pages, 1)。它给出以下错误:异常类型:KeyError 异常值:'page'。怎么了?
    • 尝试使用 max(context['page_obj']).. 而不是 max(context['page']) 看看效果如何
    • 我得到:不支持的操作数类型 -:'Page' 和 'int'。这是我的代码:bpaste.net/show/Puu0jMqkGcUqy1N9vXwH
    • 对不起,我的错误,您必须使用 context['page_obj'].number 来获取页码。您还可以看到这个问题 stackoverflow.com/questions/5907575/… 和新分页 Page 类的文档(在您的 context['page_obj'] 变量中)docs.djangoproject.com/en/dev/topics/pagination/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 2016-04-21
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2015-12-08
    相关资源
    最近更新 更多