[Python] How to show following count in template django

Discussão em 'Python' iniciado por Stack, Julho 1, 2025.

  1. Stack

    Stack Membro Participativo

    I was able to get count for follower/following users, but when user A follow user B, user B accept user A follow request(they are in friends list). After accept request, I want to display count (1) for user A Follower List and user B following list... So it looks like this: user A follower (1) following (1).... For user B follower (1) following (1). Just as the attached image on my question.....

    For example like instagram: If user A send a follow request to user B, in user A profile it shows 1 following, 0 follower and user B profile shows 1 follower, 0 following.. When user B accept user A friend request, then it shows in profile of user A 1 follower, 1 following... user B 1 follower, 1 following.

    [​IMG]

    [​IMG]

    [​IMG]

    [​IMG]

    [​IMG]

    class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
    friends = models.ManyToManyField('Profile', related_name="my_friends", blank=True)


    class FriendRequest(models.Model):
    from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user')
    to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user')


    def ProfileView(request, username):
    #Follow requests
    my_friend_ids = set(
    request.user.profile.friends.values_list('user', flat=True)
    )
    my_pending_friend_requests = set(FriendRequest.objects.filter(from_user=request.user).values_list('to_user_id', flat=True))
    my_reverse_friend_requests = set(FriendRequest.objects.filter(to_user=request.user).values_list('from_user_id', flat=True))

    user = request.user
    friends_received = FriendRequest.objects.filter(to_user=user)
    # Option 2: Get users that have sent friend requests to the current user
    friends_sent = FriendRequest.objects.filter(from_user=user)


    #Template
    {% for post in posts %}
    <div>{{ post.poster_profile }}</div>
    {% if post.poster_profile_id in my_friend_ids %}
    <button>Unfriend</button>
    {% elif post.poster_profile_id in my_pending_friend_requests %}
    <button>Pending</button>
    {% elif post.poster_profile_id in my_reverse_friend_requests %}
    <button>Accept</button>
    {% else %}
    <button>Send Friend Request</button>
    {% endif %}

    <div>{{ post.caption }}</div>
    {% endfor %}


    #Follower/Following count
    <p><b>{{ friends_sent|length|humanize_number }}</b> Following</p>
    <p><b>{{ friends_received|length|humanize_number }}</b> Followers</p>

    Continue reading...

Compartilhe esta Página