Reputation: 589
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.
Upvotes: 0
Views: 1565
Reputation: 56
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")
Upvotes: 1