You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django类视图加自定义装饰器报错,函数视图正常的原因及解决

Django类视图装饰器报错原因与解决方法

报错原因

你编写的authenticated_user装饰器是为函数视图设计的,直接套用在类视图的方法上时,参数传递逻辑不匹配。类视图的方法第一个参数是类实例self,而非request;但你的装饰器把第一个参数当成request去访问request.user,实际拿到的是ProfessorRegister类的实例,这个实例本身没有user属性,因此抛出AttributeError。

解决方法

方法1:修改装饰器适配类视图方法参数

调整装饰器的参数结构,先接收类实例self,再接收request:

from django.shortcuts import redirect

def authenticated_user(view_func):
    def wrapper_func(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return view_func(self, request, *args, **kwargs)
        else:
            return redirect('/')
    return wrapper_func

修改后即可直接在类视图的get方法上使用该装饰器。

方法2:使用Django内置method_decorator(推荐)

Django提供了method_decorator工具,能直接将函数装饰器转换为适配类视图方法的装饰器,无需修改原有装饰器代码:

from django.utils.decorators import method_decorator
from .decorators import authenticated_user

class Signup(View):
    @method_decorator(authenticated_user)
    def get(self, request):
        # 你的视图逻辑
        ...

也可以将装饰器直接应用在类上,指定作用的方法名:

from django.utils.decorators import method_decorator
from .decorators import authenticated_user

@method_decorator(authenticated_user, name='get')
class Signup(View):
    def get(self, request):
        # 你的视图逻辑
        ...

内容的提问来源于stack exchange,提问作者kurac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:40:33