【问题标题】:AttributeError: ​module 'django.http.request' has no attribute 'user // i have Django rest installedAttributeError:​模块'django.http.request'没有属性'用户//我安装了Django rest
【发布时间】:2021-09-13 10:15:20
【问题描述】:

我遇到的错误

AttributeError: 模块 'django.http.request' 没有属性 'user'

我尝试在用户登录时发送的信号

def auth_done(sender, **kwargs):
    print('User has logged in')
    tok = Token.objects.create(user=request.user)
    print(tok.key())


user_logged_in.connect(auth_done, sender=User)

登录视图

@csrf_exempt
def login_in(request):
    if request.method == 'POST':
        name = request.POST['first_name']
        password = request.POST['password']

        user = authenticate(username=name, password=password)
        if user is not None:
            print(user)
            login(request, user)
            tok = Token.objects.create(user=request.user)
            print(tok.key)
            print('User is authenticated')
        else:
            print('Not authenticated')
    return render(request, 'Auth/user.html')

设置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
# Use Django's standard `django.contrib.auth` permissions,

    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.isAuthenticated'
    ]
}

【问题讨论】:

    标签: django django-rest-framework django-authentication


    【解决方案1】:

    在您的函数auth_done 中,您尝试访问request.user,这里的request 到底是什么?我假设您有一个如下所示的导入并尝试将其用作请求:

    from django.http import request
    

    这里的request不是你想的那样,它是module,里面包含了请求类的定义(HttpRequest等)。相反,您希望将来自 关键字参数 的请求传递给信号,或者实际上您甚至不希望这样,因为 user 也作为关键字参数传递:

    def auth_done(sender, **kwargs):
        print('User has logged in')
        # tok = Token.objects.create(user=kwargs['request'].user)
        tok = Token.objects.create(user=kwargs['user'])
        print(tok.key())
    
    
    user_logged_in.connect(auth_done, sender=User)
    

    进一步看来,您似乎在不必要地复制此代码,因为您的login_in 在用户登录后在做同样的事情。

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2017-02-16
      • 2022-01-25
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多