Updating user profile using django rest framework api

I want to create an API where the user can update their profile. In my case, the user can update his username and password. To change your profile, the API link must be /api/change/usernameOfThatUser . When I use a nonexistent username in the link, I still get the API page of the user API, and the input fields are not populated 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'), 
+6
source share
1 answer

Perhaps try doing something similar instead in 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 the existing data for the user based on the username provided in the URL. If the username does not exist, it will result in a 404 error. You can also update or delete the object.

+7
source

All Articles