Django + React 基于会话的身份验证“AnonymousUser”对象没有属性“_meta”

问题描述 投票:0回答:1

我正在学习 Django 和 React。我创建了一个基于会话的小型身份验证应用程序,尝试运行良好,然后我通过“注销”来破坏它。现在无法登录。总是返回以下错误:

AttributeError:“AnonymousUser”对象没有属性“_meta”。 “POST /api/login/HTTP/1.1”500 75814

这是我的 api/views.py 代码:

from django.shortcuts import render

# Create your views here.
import json
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_POST

@require_POST
def login_view(request):
    data = json.loads(request.body)
    username = data.get("username")
    password = data.get("password")

    if username is None or password is None:
        return JsonResponse({"details": "Please provide both username and password"})
    
    user = authenticate(request, username=username, password=password)

    if user is not None:
        return JsonResponse({"details": "invalid username and password"}, status=400)
    
    login(request, user)
    return JsonResponse({"details": "login successful"})

def logout_view(request):
    if not request.user.is_authenticated:
        return JsonResponse({"details": "you are not logged in"}, status=400)
    logout(request)
    request = JsonResponse({"details": "logout successful"})

@ensure_csrf_cookie
def session_view(request):
    if not request.user.is_authenticated:
        return JsonResponse({"isauthenticated": False})
    return JsonResponse({"isauthenticated": True})

def whoami_view(request):
    if not request.user.is_authenticated:
        return JsonResponse({"isauthenticated": False})
    return JsonResponse({"username": request.user.username})

非常感谢您的帮助!

我尝试:

  • 在管理面板上创建另一个用户。
  • 重启服务器
  • 编辑views.py
  • 网上搜索

编辑 它来自我的 app.jsx。我的用户名和用户名之间有一个拼写错误。

python reactjs django authentication
1个回答
0
投票

App.jsx 中用户名和用户名之间存在拼写错误。

© www.soinside.com 2019 - 2024. All rights reserved.