首页 > 解决方案 > 尝试连接到使用 Django 准备的 API 时收到错误请求警告

问题描述

我有一个用 django 准备的用户 API。但是,当我出于测试目的使用 Postman 应用程序发出 API 请求时,我收到 400 Bad Request 警告,这可能是什么原因?如果有任何其他需要的代码,我可以如下编写我的所有代码。

这是views.py 代码

    from rest_framework_simplejwt.views import TokenObtainPairView
    from rest_framework import status
    from rest_framework.response import Response
    from rest_framework.views import APIView
    from .serializers import CustomUserSerializer
    from rest_framework_simplejwt.tokens import RefreshToken
    from rest_framework.permissions import AllowAny
    
    
    class CustomUserCreate(APIView):
        permission_classes = [AllowAny]
    
        def post(self, request, format='json'):
            serializer = CustomUserSerializer(data=request.data)
            if serializer.is_valid():
                user = serializer.save()
                if user:
                    json = serializer.data
                    return Response(json, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    
    class BlacklistTokenUpdateView(APIView):
        permission_classes = [AllowAny]
        authentication_classes = ()
    
        def post(self, request):
            try:
                refresh_token = request.data["refresh_token"]
                token = RefreshToken(refresh_token)
                token.blacklist()
                return Response(status=status.HTTP_205_RESET_CONTENT)
            except Exception as e:
                return Response(status=status.HTTP_400_BAD_REQUEST)

这是我的网址

api/urls.py

from django.urls import path
from .views import CustomUserCreate, BlacklistTokenUpdateView

app_name = 'users'

urlpatterns = [
    path('create/', CustomUserCreate.as_view(), name="create_user"),
    path('logout/blacklist/', BlacklistTokenUpdateView.as_view(),
         name='blacklist')
]

核心/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)


urlpatterns = [
    path('admin/', admin.site.urls),
    path("api/post/", include("post.api.urls", namespace="post")),
    path("api/post/audio/", include("post_audio.api.urls", namespace="postaudio")),
    path('api/comment/', include('comment.api.urls', namespace='comment')),
    path("api/categories/", include("post.api.urls", namespace="categories")),
    path("api/author/", include("author.api.urls", namespace="author")),
    path("api/favourites/", include("favourite.api.urls", namespace="favourite")),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

这也是我的 serializers.py 代码

from rest_framework import serializers
from users.models import NewUser


class CustomUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True)
    user_name = serializers.CharField(required=True)
    password = serializers.CharField(min_length=8, write_only=True)

    class Meta:
        model = NewUser
        fields = ('email', 'user_name', 'password')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        # as long as the fields are the same, we can just use this
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

标签: pythondjangoapirestdjango-rest-framework

解决方案


400 错误可能表明问题在于您如何从该工具构建请求。

您发送的电子邮件值不是有效的电子邮件格式,而且您似乎也没有发送用户名,所以我怀疑请求在序列化程序级别验证失败。


推荐阅读