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

Django类视图加@login_required报'object has no attribute 'user''错误

错误原因

你使用的@login_required是函数视图专属装饰器,不能直接用于装饰类视图的实例方法。
类视图的实例方法第一个参数永远是类自身的实例对象self,而非请求对象request。你直接把@login_required加在get方法上时,装饰器会把传入的self当成request对象处理,尝试访问self.user属性,而你的play类本身没有user属性,就触发了对应的AttributeError。

解决方案

方案1:搭配method_decorator使用login_required

你需要先用Django提供的method_decorator把函数装饰器转换成适配类方法的装饰器,有两种写法:

  1. 装饰整个类的dispatch方法(所有请求方法都会触发登录校验):
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class play(View):
    def get(self, request, *args, **kwargs):
        print("GET request: ", request)
        return render(request, 'play.html', {})
  1. 仅装饰get方法(只有GET请求会触发登录校验):
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class play(View):
    @method_decorator(login_required)
    def get(self, request, *args, **kwargs):
        print("GET request: ", request)
        return render(request, 'play.html', {})

方案2:使用LoginRequiredMixin(更推荐)

Django专门为类视图提供了登录校验Mixin,无需额外装饰,继承即可生效,默认会自动读取你settings.py中配置的LOGIN_URL完成跳转,完全符合你未登录跳转到home路由的需求:

from django.contrib.auth.mixins import LoginRequiredMixin

class play(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        print("GET request: ", request)
        return render(request, 'play.html', {})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 03:30:05