Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating user profile using django rest framework api

I want to create an API where user can update their profile. In my case, a user can update his/her username and password. To change his/her profile, an API link should be /api/change/usernameOfThatUser. When I use a non-existing username in the link, I still get the userProfileChange API page, and the input boxes are not filled with previous data. How can I solve this?

serializers.py

User = get_user_model()

class UserProfileChangeSerializer(ModelSerializer):
    username = CharField(required=False, allow_blank=True, initial="current username")
    class Meta:
        model = User
        fields = [
            'username',
            'password',
        ]

    def update(self, instance, validated_data):
        instance.username = validated_data.get('username',instance.username)
        print('instance of username',instance.username)
        return instance 

views.py

class UserProfileChangeAPIView(UpdateAPIView):
    serializer_class = UserProfileChangeSerializer
    lookup_field = 'username'

urls.py

  url(r'^change/(?P<username>[\w-]+)$', UserProfileChangeAPIView.as_view(), name='changeProfile'),
like image 668
pri Avatar asked Jul 18 '16 10:07

pri


1 Answers

Maybe try doing something like this instead in your views.py?

from rest_framework import generics, mixins, permissions

User = get_user_model()

class UserIsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.id == request.user.id

class UserProfileChangeAPIView(generics.RetrieveAPIView,
                               mixins.DestroyModelMixin,
                               mixins.UpdateModelMixin):
    permission_classes = (
        permissions.IsAuthenticated,
        UserIsOwnerOrReadOnly,
    )
    serializer_class = UserProfileChangeSerializer
    parser_classes = (MultiPartParser, FormParser,)

    def get_object(self):
        username = self.kwargs["username"]
        obj = get_object_or_404(User, username=username)
        return obj

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

This will give you all of the existing data for the user based on the username passed in the url. If the username does not exist, it will raise a 404 error. You can also update or delete the object.

like image 98
jape Avatar answered Sep 22 '22 19:09

jape