gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:10:59 28 4
gpt4 key购买 nike

我正在尝试为模型查询集创建一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com