Django/python : 'function' object has no attribute 'as_view'

标签 django django-views django-urls django-generic-views

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

这是我的代码:

View .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)

网址.py:
 url(r'^live_bids/$', live_bids.as_view()),

最佳答案

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

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那里。
class LiveBids(LoginRequiredMixin, ListView):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(LiveBids, self).dispatch(*args, **kwargs)

最简单的解决方案是使用 LoginRequiredMixin 而不是装饰器(适用于 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)

请注意,在示例中,我已将 View 重命名为 LiveBids , 以匹配推荐的 Django 风格。您还必须更新 url 模式。

关于Django/python : 'function' object has no attribute 'as_view' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38724387/

相关文章:

python - 从 Django 开发服务器的根目录提供静态文件

Django 说它必须是一个模型实例

python - 我怎样才能在模型表单中拥有相当于 django 的管理内联功能?

django - 没有名为默认值的模块 Django-Simple-Friends

python - 类型错误 : view must be a callable or a list/tuple when including another urls. py

python - django 警告 urls.W005 URL 命名空间不唯一

python - 在 factory_boy 中更改默认的 faker 语言环境

python - 为什么我在 Django Rest Framework 中得到 "AssertionError: May not set both ` read_only` 和 `required` “?

django - Python Celery group() - TypeError : [. ..] ** 之后的参数必须是一个映射,不长

django - Django 平面页面的 View ?