ValidationError'用户的HTTP代码已存在'

时间:2017-07-12 00:13:08

标签: python django http django-rest-framework

我正在使用Django Rest Framework为我的Django项目做一个登录应用程序。

在注册时,在我的序列化程序中,我通过这样做来检查用户是否已经存在:

def create(self, validated_data):
    """                                                                                               
    Create an user but validate datafirst(checking if exist,                                          
    if mail is right,not already in-use, and hash password).                                          
    """
    queryset = PictureUser.objects.filter(username=validated_data['username'])
        try:
            queryset[0]
            raise serializers.ValidationError('The username is already used.')
        except IndexError:
            print ("User don't exist.")
            user = PictureUser.objects.create(
                email = validated_data['email'],
                username = validated_data['username'],
                password = make_password(validated_data['password']),
            )
            user.save()
            return user

这项工作很顺利。但是当用户已经存在时,发送的HTTP代码为400。如何将其更改为409422,以便在出现问题时更准确? (400错误意味着许多其他错误。)

我必须返回一个HttpResponse吗?

感谢。

1 个答案:

答案 0 :(得分:1)

您无法在序列化程序中执行此操作。

也许你可以拥有这样的东西:

view.py

class YourView(APIView):

    def post(self, request, format=None):
        serializer = YourSerializer(data=request.data)
        if serializer.is_valid():
            return Response({'yourinfo':'something'}, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_409_CONFLICT) # change it to 

serializer.py

class YourSerializer(serializers.ModelSerializer):

    # Override this if you want. Default Django Auth
    username = serializers.CharField()
    password = serializers.CharField()
    class Meta:
        model = User
    def validate(self, attrs):

        username = attrs['username']
        password = attrs['password']

        # do your validations here

        if everything_ok:
            return attrs
        else:
            raise serializers.ValidationError("User does not belong to API group")