'Updating Profile image of a UserProfile linked to a user with OneToOne Relations

I was able to automaticcaly create a userProfile everytime a user is created but I want to be able to modify somefields in the userprofile.

So my Model.py

def upload_path(instance,filename):
      return 'users/avatars/{0}/{1}'.format(instance.user.username, filename)

class UserProfile(models.Model):
      user= models.OneToOneField(User,on_delete=models.CASCADE, related_name='userprofile')

      Profileimage= models.ImageField(upload_to=upload_path, blank=True, null=True, default='user/avatar.jpeg')
      def __str__(self):
          return self.user.username

@ receiver(post_save,sender=User)
def create_user_profile(sender,instance,created,**kwargs):
     if created:
         UserProfile.objects.create(user=instance)

My Serializer.py

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields =['id', 'username','password','email']
    extra_kwargs={'password':{'write_only':True, 'required':True}}

def create(self,validated_data):
    user =User.objects.create_user(**validated_data)
    Token.objects.create(user=user)
    return user

class UserProfileSerializer(serializers.ModelSerializer):
user=serializers.SlugRelatedField(queryset=models.User.objects.all(),      slug_field='username')
class Meta:
    model =models.UserProfile
    
    #lookup_field = 'username'
    fields= '__all__'

My view.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'username'


class UserProfileViewSet(viewsets.ModelViewSet):
    
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    
    

Using postman i get the error : django.db.utils.IntegrityError: UNIQUE constraint failed: api_userprofile.user_id



Solution 1:[1]

So after adding

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

I was able to change the fields that I want to.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1