Hy, I am trying to make a twitter clone using django however I am having issues implementing following and follower system. Suppose I have 2 users A and B. If A follows B, B should be in user A following List furthermore user A should be in user B followers List. However my code seems to implement the reverse and I am confused. e.g I if I follow elon musk he would be in my following list but I would be in his followers list
Models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True, max_length=30)
profile_picture = models.ImageField(upload_to="images/profile/",default='default.png')
following = models.ManyToManyField(User, symmetrical=False, blank=True,related_name='all_following')
followers = models.ManyToManyField(User, symmetrical=False, blank=True, related_name='all_followers')
def __str__(self):
return str(self.bio)
def get_absolute_url(self):
return reverse('home')
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
print('Profile Created')
post_save.connect(create_profile,sender=User)
def update_user_profile(sender, instance, created, **kwargs):
if created == False:
instance.profile.save()
print('Profile Updated')
post_save.connect(update_user_profile, sender=User)
def profile_picURL(self):
try:
url = self.profile_pic.url
except:
url = " "
return url
HTML CODE SNIPPET
<div class="column3">
{% for user in users%}
{% if not request.user == user%}
<div class="follow-users">
<h5>{{user.username}}</h5>
<div class="follow-user">
<div>
<span>{{user.all_followers.all.count}} followers</span>
<span>{{user.all_following.all.count}} following</span>
<p><a href="{% url 'view_user_profile' user.id %} ">View {{user.username}} profile</a></p>
</div>
<form action="{% url 'follow_unfollow_user' user.id %}" method="POST" class="ml-5">
{% csrf_token %}
{% if user.profile.followers.all %}
{% if request.user in user.profile.followers.all %}
<button type="submit" value = "{{user.id}}" class="btn btn-danger btn-sm">Unfollow</button>
{% else %}
<button type="submit" value = "{{user.id}}" class="btn btn-primary btn-sm">Follow</button>
{% endif %}
{% else %}
<button type="submit" value = "{{user.id}}" class="btn btn-primary btn-sm">Follow</button>
{% endif %}
</form>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</section>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…