Search code examples
djangodjango-rest-frameworkmixinsputupdatemodel

How to update user profile through Mixins in Django


Need to edit user profile using mixins, by sending a PUT request to corresponding url (that contains the id of the user whose info is to be updated )

What is missing/needs to be changed in the following code to achieve the above?

models.py:

class UserProfile(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User)
    profile_picture = models.ImageField(upload_to='documents', blank=True)
    def __str__(self):
        return self.user.username

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username','password', 'first_name', 'last_name', 'email',)
        write_only_fields = ('password',)
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',)

        def restore_object(self, attrs, instance=None):
            user = super(UserSerializer, self).restore_object(attrs, instance)
            user.set_password(attrs['password'])
            return user

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = UserProfile
        fields = ('id','user','profile_picture',)

views.py

class UserMixin(object,):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = (IsOwnerOrReadOnly,)

class UserProfileView(UserMixin, RetrieveUpdateDestroyAPIView):
    pass

Do ask if more clarity is required.


Solution

  • Can you use ModelViewsets for updating the user-profile

    class UserProfileViewViewSet(viewsets.ModelViewSet):
            queryset = UserProfile.objects.all()
            serializer_class = UserProfileSerializer
            permission_classes = (IsOwnerOrReadOnly,)
    
            def update(self, request, *args, **kwargs):
                user_profile = self.get_object()
                serializer = self.get_serializer(user_profile, data=request.data, partial=True)
                serializer.is_valid(raise_exception=True)
                self.perform_update(serializer)
                return Response(serializer.data)