CSRF失败:缺少CSRF令牌,关于Django Rest

sz81bmfz  于 2023-06-25  发布在  Go
关注(0)|答案(2)|浏览(170)

我真的很困惑,因为我无法避免这个错误。我以前的项目没有遇到这个错误。无论如何,我希望你能找到解决办法。
这里是我的settings.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "rest_framework",
    "accounts",
    "contents",
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication"
    ]
}
WSGI_APPLICATION = 'config.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'
STATIC_ROOT = os.path.join("static")
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

这是我的网站urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("accounts/", include("accounts.urls")),
    path("contents/", include("contents.urls")),
]

这里是帐户。意见:

from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework import status
from rest_framework.views import APIView
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate

from accounts.serializers import UserCreationSerializer, UserLoginSerializer

class RegisterAPIView(CreateAPIView):
    model = User
    queryset = User.objects.all()
    serializer_class = UserCreationSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        username = serializer.validated_data.get("username")
        password = serializer.validated_data.get("password")
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return Response(
                data={"msg": "User created successfully and logged in"},
                status=status.HTTP_201_CREATED
            )
        return Response(
            data={"msg": "User Creation process failed"}, status=status.HTTP_400_BAD_REQUEST
        )

    def perform_create(self, serializer):
        serializer.save()

class UserLoginView(APIView):
    def post(self, request):
        serializer = UserLoginSerializer(data=request.data)
        print(request.user.is_authenticated)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK)
            else:
                return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class LogoutAPIView(APIView):
    model = User

    def get(self, request, *args, **kwargs):
        logout(request)
        return Response(data={"msg": "User logged out successfully!"}, status=status.HTTP_200_OK)

accounts.urls

from django.urls import path
from accounts import views

urlpatterns = [
    path("register/", views.RegisterAPIView.as_view(), name="register"),
    path("login/", views.UserLoginView.as_view(), name="login"),
    path("logout/", views.LogoutAPIView.as_view(), name="logout")
]

accounts.serializers

from rest_framework import serializers

from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class UserCreationSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ["username", "first_name", "last_name", "email", "password"]
        model = User

    def save(self, **kwargs):
        user = self.Meta.model
        return user.objects.create_user(
            username=self.validated_data.get("username"),
            email=self.validated_data.get("email"),
            password=self.validated_data.get("password"),
            first_name=self.validated_data.get("first_name"),
            last_name=self.validated_data.get("last_name"),
        )

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150)
    password = serializers.CharField(max_length=128, write_only=True)

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise serializers.ValidationError("Invalid username or password.")
        else:
            raise serializers.ValidationError("Both username and password are required.")

        data['user'] = user
        return data

这是 Postman 快照。

这些都是我可以显示为代码,如果这个problem不依赖于我的代码,好吧,让我知道,我不知道其他可能性,导致这个错误,但所有的配置,如谷歌, Postman ,Python和编辑器是完美的,就像他们工作得很好。
我在生产,所以希望你们能找到适当的解决方案。提前感谢。
你的阿布杜萨马德

iklwldmw

iklwldmw1#

我研究了一下,找到了一个答案,这是一个愚蠢的错误,你应该把sessionauthentication改为tokenauthentication或其他支持的类,在www.example.com的REST_FRAMEWORK变量中settings.py,这是多么愚蠢的情况,不是吗?

hvvq6cgz

hvvq6cgz2#

帐户中存在问题。url,请使用

path("register/", views.RegisterAPIView().as_view(), name="register"),
path("login/", views.UserLoginView().as_view(), name="login"),
path("logout/", views.LogoutAPIView().as_view(), name="logout")

因为RegisterAPIView()、UserLoginView()、LogoutAPIView()是类
你也可以试试

class RegisterAPIView(CreateAPIView):
    model = User
    queryset = User.objects.all()
    serializer_class = UserCreationSerializer
    @staticmethod
    def post(self, request, *args, **kwargs):
   ....

在帐户视图中

相关问题