Issue
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.
My signals.py
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)
profile.followers.add('1')
my methods:
class AddFollower(ListView):
def post(self, request, pk , *args, **kwargs ):
print('usuario aaaaaaaaaaaaaaaaaagregado')
profile = Profile.objects.get(pk = pk)
profile.followers.add(self.request.user)
return redirect('profile', username = profile.user.username)
class RemoveFollower(ListView):
def post(self, request, pk , *args, **kwargs ):
print(f'reeeeeeeeeeeeeeeeeeeeeeeemovingFollower2{request.user}')
profile = Profile.objects.get(pk = pk)
profile.followers.remove(self.request.user)
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'
Solution
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 signals.py
profile.followers.add('1')
should be
profile.followers.add(instance)
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
Answered By - Ogieleguea Hillary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.