Reputation: 523
I try to return a custom Response for my generics API view but it does not work since I get 'Response' object has no attribute 'username' error when the API is called
Here's what I've done so far:
I handle the DoesNotExist exception error then return a Response (from django rest framework).
class UniqueEmailAPI(generics.RetrieveAPIView):
permission_classes = [
permissions.AllowAny,
]
serializer_class = UserSerializer
def get_object(self):
email = self.request.data['email']
try:
return User.objects.get(email= email)
except ObjectDoesNotExist:
return Response(status=status.HTTP_204_NO_CONTENT)
UserSerializer:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
Exception Log: Stacktrace
Upvotes: 1
Views: 76
Reputation: 11484
Your serializer is trying to serialize your Response(status=status.HTTP_204_NO_CONTENT)
response. It will try to serialize anything you return from get_object
with your serializer unless you raise an error.
You can raise a 404 error using Django's get_object_or_404
method for the framework to know it should return an error response instead.
You could do something this:
from django.shortcuts import get_object_or_404
get_object_or_404(User, email= email)
Upvotes: 1