I'm trying to return the details of the current logged in user in the following way:
from .serializers import UserSerializer
class UserDetailsView(RetrieveAPIView):
model = User
queryset = User.objects.all()
permission_classes = [permissions.IsAuthenticated]
serializer_class = UserSerializer
def get(self, request, *args, **kwargs):
user = User.objects.get(id=request.user.id)
print(user)
return Response(user)
in serializers.py I've use ModelSerializer
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
fields = ('id', 'username', 'password')
write_only_fields = ('password',)
I get an error Object of type 'User' is not JSON serializable
. What is wrong in my use case?
You need to return
return Response(serializer.data)
in your get function under UserDetailsView. More details here.
DRF response should be JSON-like objects, to convert model instanse to it you use seralizer class:
def get(self, request, *args, **kwargs):
user = User.objects.get(id=request.user.id)
serializer = self.get_serializer(user)
return Response(serializer.data)
Also you dont need additional query to get current user, you can user request.user
directly:
serializer = self.get_serializer(request.user)
return Response(serializer.data)
Please check you are returning value of particular field in serializer get method, not entire user object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With