ValidationError HTTP Code for 'user already exist'

Addict

I'm doing a login app for my Django project using Django Rest Framework.

At registration, in my serializer, i'm checking if user already exist by doing this:

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

This work pretty well. But the HTTP code sent is 400 when the user already exist. How can I change it to 409 or 422 to be more accurate on what went wrong ? (400 error would imply many other errors.)

Must I return an HttpResponse instead?

Thanks.

Alina

You can't do that in the serializer.

Maybe you can have something like this:

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")

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

what is the code in php to check if user already Exist or not?

From Dev

what is the code in php to check if user already Exist or not?

From Dev

Parse check if user already exist

From Dev

How to stop the user is already exist validation in django?

From Dev

Chef: Initialize new linux user if it doesn't already exist

From Dev

Check if email already exist error undefined index: user_id

From Dev

HTTP response code for refund already done

From Dev

Forms ValidationError and error code

From Dev

Forms ValidationError and error code

From Dev

Check if name already exist

From Dev

sqlite python if already exist?

From Dev

Correct code location to check Firebase if a user has been created already?

From Dev

HTTP Status Code for username already exists when registering new account

From Java

HTTP response code for POST when resource already exists

From Dev

What is an appropriate HTTP response code for a file that already exists?

From Dev

What is an appropriate HTTP response code for a file that already exists?

From Dev

User friendly message with http status code 500

From Dev

Django REMOTE_USER does not exist but HTTP_REMOTE_USER does

From Dev

value already exist using bootstrapvalidation on codeigniter if value already exist

From Dev

Note Code : 1973 Can't create user 'user'@'localhost'; it already exists, Mysql

From Dev

Check whether data already exist or not

From Dev

Validate if data already exist in firebase

From Dev

xquery skip elements if they exist already

From Dev

Check if username already exist in DB

From Dev

Check if value already exist in SQL

From Dev

Check if user is already logged in

From Dev

ReflectionException in compiled.php line 1049: Class App\Http\Controllers\User does not exist

From Dev

What status code should be sent when a user tries to sign up with a username that already exists?

From Dev

What status code should be sent when a user tries to sign up with a username that already exists?

Related Related

  1. 1

    what is the code in php to check if user already Exist or not?

  2. 2

    what is the code in php to check if user already Exist or not?

  3. 3

    Parse check if user already exist

  4. 4

    How to stop the user is already exist validation in django?

  5. 5

    Chef: Initialize new linux user if it doesn't already exist

  6. 6

    Check if email already exist error undefined index: user_id

  7. 7

    HTTP response code for refund already done

  8. 8

    Forms ValidationError and error code

  9. 9

    Forms ValidationError and error code

  10. 10

    Check if name already exist

  11. 11

    sqlite python if already exist?

  12. 12

    Correct code location to check Firebase if a user has been created already?

  13. 13

    HTTP Status Code for username already exists when registering new account

  14. 14

    HTTP response code for POST when resource already exists

  15. 15

    What is an appropriate HTTP response code for a file that already exists?

  16. 16

    What is an appropriate HTTP response code for a file that already exists?

  17. 17

    User friendly message with http status code 500

  18. 18

    Django REMOTE_USER does not exist but HTTP_REMOTE_USER does

  19. 19

    value already exist using bootstrapvalidation on codeigniter if value already exist

  20. 20

    Note Code : 1973 Can't create user 'user'@'localhost'; it already exists, Mysql

  21. 21

    Check whether data already exist or not

  22. 22

    Validate if data already exist in firebase

  23. 23

    xquery skip elements if they exist already

  24. 24

    Check if username already exist in DB

  25. 25

    Check if value already exist in SQL

  26. 26

    Check if user is already logged in

  27. 27

    ReflectionException in compiled.php line 1049: Class App\Http\Controllers\User does not exist

  28. 28

    What status code should be sent when a user tries to sign up with a username that already exists?

  29. 29

    What status code should be sent when a user tries to sign up with a username that already exists?

HotTag

Archive