Django/python:'function' 对象没有属性 'as_view' [英] Django/python: 'function' object has no attribute 'as_view'

查看:34
本文介绍了Django/python:'function' 对象没有属性 'as_view'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为模型查询集创建一个 list_view.运行我的服务器时,它返回:属性错误-函数"对象没有属性as_view".如果能帮我解决这个问题,我将不胜感激.

I am trying to create a list_view for a model queryset. When running my server, it returns : attribute error - 'function' object has no attribute 'as_view'. I would appreciate helping me in solve this.

这是我的代码:

Views.py:

@login_required 
class live_bids(ListView):

    model = Post 
    template_name = 'loggedin_load/live_bids.html'

    def get_queryset(self):
        return Post.objects.all().prefetch_related('bids').filter(user=self.request.user)

urls.py:

 url(r'^live_bids/$', live_bids.as_view()),

推荐答案

你不能在这样的类上使用 login_required 装饰器.您需要使用 method_decorator.在 Django 1.9+ 上,你可以装饰类:

You can't use the login_required decorator on a class like that. You need to use method_decorator. On Django 1.9+, you can decorate the class:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class LiveBids(LoginRequiredMixin, ListView):
    ...

在早期版本中,您需要覆盖 dispatch 并在那里使用 method_decorator.

On earlier versions, you need to override dispatch and use method_decorator there.

class LiveBids(LoginRequiredMixin, ListView):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LiveBids, self).dispatch(*args, **kwargs)

最简单的解决方案是使用LoginRequiredMixin 而不是装饰器(适用于 Django 1.9+)

The easiest solution is to use LoginRequiredMixin instead of the decorator (works with Django 1.9+)

from django.contrib.auth.mixins import LoginRequiredMixin

class LiveBids(LoginRequiredMixin, ListView):
    model = Post 
    template_name = 'loggedin_load/live_bids.html'

    def get_queryset(self):
        return Post.objects.all().prefetch_related('bids').filter(user=self.request.user)

请注意,在示例中,我已将视图重命名为 LiveBids,以匹配推荐的 Django 样式.您还必须更新网址格式.

Note that in the examples, I have renamed the view to LiveBids, to match the recommended Django style. You'll have to update the url pattern as well.

这篇关于Django/python:'function' 对象没有属性 'as_view'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆