1

I am using django rest framework and I have created a view to update a user.

Here is my view:

def put(self, request, *args, **kwargs):
    authorization =UserSuitsPermissions().superuser(request.user)
    userpk = kwargs.get('pk', 0)
    user = get_object_or_404(STUser, pk=userpk)
    if not authorization:
        if request.user['id'] == user.id:
            authorization = True
    if authorization:
        serializeddata = UserSerializer(data=request.data)
        if serializeddata.is_valid(raise_exception=True):
            data = serializeddata.validated_data
            user.__dict__.update(**data)
            user.save()
            serialzed = UserSerializer(user)
            return Response(serialzed.data)
    return Response(status=status.HTTP_401_UNAUTHORIZED)

now in this linked question they are using a generic view and using the serializer to update the user instance :

Django DRF Update User

with the accepted answer being:

def update(self, request, *args, **kwargs):
    serializer = self.serializer_class(request.user, data=request.data, partial=True)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data, status=status.HTTP_200_OK)

I am not using a generic view and in truth Im over them. I dont value it. so the question is, how do we update a user object via the api view?

my biggest question is does this line in the accepted answer have relevance to my code?

serializer = self.serializer_class(request.user, data=request.data, partial=True)

1 Answers1

2

soooo

I figured it out.

the correct way is to pass an instance to a serializer then call save with the partial flag set to true.

the code looks like this:

serializeddata = UserSerializer(user, data=request.data, partial=True)
            if serializeddata.is_valid(raise_exception=True):
                serializeddata.save()
                return Response(serializeddata.data)

with the full view looking like:

def put(self, request, *args, **kwargs):
        authorization =UserSuitsPermissions().superuser(request.user)
        userpk = kwargs.get('pk', 0)
        user = get_object_or_404(STUser, pk=userpk)
        if not authorization:
            if request.user['id'] == user.id:
                authorization = True
        if authorization:
            serializeddata = UserSerializer(user, data=request.data, partial=True)
            if serializeddata.is_valid(raise_exception=True):
                serializeddata.save()
                return Response(serializeddata.data)
        return Response(status=status.HTTP_401_UNAUTHORIZED)

so thats cool