为什么电子邮件在django rest API中不显示为Json响应

ih99xse1  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(111)

查看

class UserRegistrationView(APIView):
    def post(self, request):
        serializer = UserRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            token = Token.objects.create(user=user)
            response_data = {
                'token': token.key,
                'message': 'User registration successful.'
            }
            return Response(response_data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

串行化器

class UserRegistrationSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = User
        fields = ('username', 'email', 'password')
    
    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
            email=validated_data['email']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    def validate_username(self, data):
        if User.objects.filter(username=data).exists():
            raise serializers.ValidationError("Username already exists.")
        return data
    
    def validate_email(self, data):
        if User.objects.filter(email=data).exists():
            raise serializers.ValidationError("Email already exists.")
        return data

url

path('reg/',UserRegistrationView.as_view(), name='userreg' )

在我的帖子请求中,我只得到了
{ "username": [ "This field is required." ], "password": [ "This field is required." ] }
在这个序列化器中,我传递了用户名、密码和电子邮件等字段。但是我只得到了电子邮件和用户名作为JSON响应,为什么电子邮件不显示为JSON响应。

mklgxw1f

mklgxw1f1#

电子邮件未显示在Json响应中,因为您没有在response_datadict中发送电子邮件字段。您可以像这样添加电子邮件:

class UserRegistrationView(APIView):
    def post(self, request):
        serializer = UserRegistrationSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            token = Token.objects.create(user=user)
            response_data = {
                'token': token.key,
                'email': user.email,
                'message': 'User registration successful.'
            }
            return Response(response_data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

相关问题