Signals in django. Profile does not exist

For each user I create, I also create a profile with post_save signals. With that profile you can follow users using the many to many 'followers' field. When I press addfollower or removefollower I get an error that highlights : profile = Profile.objects.get(pk = pk) as the wrong line. As this error only occurs with the profiles that I create through signals, it seems to me that the problem is when I am creating the profile automatically.


from django.db.models.signals import post_save
from django.contrib.auth.models import User
from .models import Profile
from django.dispatch import receiver

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

my methods:

class AddFollower(ListView):
    def post(self, request, pk , *args, **kwargs ):
        print('usuario aaaaaaaaaaaaaaaaaagregado')
        profile = Profile.objects.get(pk = pk)
        return redirect('profile', username = profile.user.username)

class RemoveFollower(ListView):

    def post(self, request, pk , *args, **kwargs ):
        profile = Profile.objects.get(pk = pk)

        return redirect('profile', username = profile.user.username)

my profile model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_img = models.ImageField(default='user.png')
    followers = models.ManyToManyField(User,blank=True, related_name='followers')

    def __str__(self):
        return f'{self.user.username} profile'

You are adding a string instead of a user instance to the many-to-many field of your profile, so your profile is not being created.

This line in your


should be


but that would make a user follow himself, I don't know if that is the functionality you want, if not you should probably remove it from the signals

Back to Top