1

Django的新手。我有一个没有 @login_required 装饰器的视图。

网址.py

urlpatterns = [
    path('play/', play.as_view(), name='play'),

注释掉 @login_required 的 view.py

from django.contrib.auth.decorators import login_required
.
.
class play(View):
    #@login_required
    def get(self, request, *args, **kwargs):
        print("GET request: ", request)
        return render(request, 'play.html', {})

**编辑:**添加 setting.py 条目

LOGIN_URL = 'home'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

页面在浏览器中正确加载,请求在控制台上打印如下

GET request:  <WSGIRequest: GET '/play/'>
[16/Aug/2021 23:17:23] "GET /play/ HTTP/1.1" 200 3591
[16/Aug/2021 23:17:23] "GET /static/css/home.css HTTP/1.1" 200 96
[16/Aug/2021 23:17:23] "GET /static/js/home.js HTTP/1.1" 200 3544
[16/Aug/2021 23:17:23] "GET /static/js/main.js HTTP/1.1" 200 1451443
[16/Aug/2021 23:17:23] "GET /static/images/BlankPicture.png HTTP/1.1" 200 16272
Not Found: /favicon.ico
[16/Aug/2021 23:17:24] "GET /favicon.ico HTTP/1.1" 404 7793

OTOH,如果我取消注释 @login_required 行,我会收到以下错误。

AttributeError at /play/
'play' object has no attribute 'user'
Request Method: GET
Request URL:    http://127.0.0.1:8000/play/
Django Version: 2.2.12
Exception Type: AttributeError
Exception Value:    
'play' object has no attribute 'user'
Exception Location: /usr/lib/python3/dist-packages/django/contrib/auth/decorators.py in _wrapped_view, line 20
Python Executable:  /usr/bin/python3
Python Version: 3.8.10
Python Path:    
['/home/<username>/workspace/djangoapp/src',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Mon, 16 Aug 2021 23:20:17 +0000

play.html 是一个普通的 html 页面,其中只有静态 html。即使我在不​​同的选项卡上登录,也会发生错误。

我看到错误发生在 ....django/contrib/auth/decorators.py 第 20 行

        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):   <<<Here is the error

在所有其他视图中,我首先检查用户是否为 is_authenticated,然后成功使用 user.request。我想删除那个 if-else 循环并使用 @login_required 装饰器简化我的视图。

我正在关注此处的文档login_required 装饰器我的错误在哪里?

编辑:如果用户未登录,我想将用户重定向到“主页”网址。

4

1 回答 1

1

此错误是因为login_required正在读取self(这是play错误描述的视图对象),而不是request用作类内视图的装饰器时。

由于这是基于类的视图,login_required因此使用方式不同

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


@method_decorator(login_required, name='dispatch')
class play(View):
    ...

您还可以使用LoginRequiredMixin,它的工作方式类似:

from django.contrib.auth.mixins import LoginRequiredMixin


class play(LoginRequiredMixin, View):
    ...
于 2021-08-17T00:01:25.327 回答