繁体   English   中英

Django-Rest-Framework:登录序列化程序错误

[英]Django-Rest-Framework: Login Serializer Error

我正在尝试自己实现登录系统,而不是依赖第三方应用程序。 当我尝试登录时,我收到 400 Bad Request Error 说,这个 email 的用户已经存在,而不是数据,我希望它返回。

登录序列化器

class UserLoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ("email", "password")
        extra_kwargs = {"password": {"write_only":True}}

    def validate(self, data):
        email = data["email"]
        password = data["password"]
        user = UserProfile.objects.get(email = email)
        if user:
            if not user.check_password(data["password"]):
                raise serializers.ValidationError("Incoreect Password")
            return data
        raise serializers.ValidationError("User Not Found")

LoginAPIView

class UserLoginAPIView(APIView):

    def post(self, request):
        user = UserLoginSerializer(data = request.data)
        if user.is_valid():
            return Response(user.data, status = status.HTTP_200_OK)
        return Response(user.errors, status = status.HTTP_400_BAD_REQUEST)

模型.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
# Create your models here.

class UserProfileManager(BaseUserManager):
    
    def create_user(self, email, name, password = None):
        if not email:
            raise ValueError("No email provided")
        email = self.normalize_email(email)
        user = self.model(email = email, name = name)

        user.set_password(password)
        user.save(self._db)

        return user

    def create_superuser(self, email, name, password):
        user = self.create_user(email, name, password)
        user.save(self._db)

        return user


class UserProfile(AbstractBaseUser,PermissionsMixin):
    

    email = models.EmailField(unique = True)
    name = models.CharField(max_length = 120)
    objects = UserProfileManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["name"]

您收到 400 错误,因为您的序列化程序基于具有唯一emailUser model ,因此验证失败。

我认为在您的情况下使用通用Serializer器(不是ModelSerializer )会更合适,因为您不使用它将数据保存到 model。

它会是这样的:

class UserLoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)

    def validate(self, data):
        ... # your validate method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM