Home > Net >  how to serialize current user in django rest framework?
how to serialize current user in django rest framework?

Time:12-29

I wrote a custom user and defined the serializer for it, and now I have an endpoint that the user sent the get request. He should get the user information in json format. And since my response format is as follows

{
     'messages': msg,
     'data': data
}

I do not know how to serialize the user or which generic view to use my code:

class ProfileView(generics.RetrieveAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.user)
        if serializer.is_valid():
            return successful_response(
                messages=_('User Profile'),
                data=serializer.data
            )
        return unsuccessful_response(serializer.errors)

and the error I get:

{
    "errors": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got User."
        ]
    }
}

Anyone have an idea?

CodePudding user response:

you probably need to convert "user instance" to dictionary i suggest doing this:

from django.forms.models import model_to_dict #this line
class ProfileView(generics.RetrieveAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def retrieve(self, request, *args, **kwargs):
    serializer = self.serializer_class(data=model_to_dict(request.user))# instance converted to dict
        if serializer.is_valid():
            return successful_response(
                messages=_('User Profile'),
                data=serializer.data
            )
        return unsuccessful_response(serializer.errors)
  • Related