Unable to update followers and following count

Following count and followers count not updating

When a user clicks on the follow button, the current users following count is updated on the admin end but the user that was followed - Followers count does not update and the Following count does not change. How can I fix this?

VIEWS.PY

def profile(request, user_id):
    profile_user = User.objects.get(pk = user_id)
    profile_post = NewTweet.objects.filter(user = user_id)
    post_count = len(profile_post)
    follower = request.user
    user = user_id

    followers_user = len(Followers.objects.filter(user=user_id))
    following_user = len(Followers.objects.filter(follower=user_id))

    context = {
        "profile_user": profile_user,
        "post_count": post_count,
        "profile_post": profile_post,
        "followers_user": followers_user,
        "following_user": following_user,
    }

    return render(request, "network/profile.html", context)

def follow(request):
    if request.method == 'POST':
        follower = request.POST['follower']
        user = request.user

        if Followers.objects.filter(follower=follower, user=user).first():
            delete_follower = Followers.objects.get(follower=follower, user=user)
            delete_follower.delete()
            following = False
            context = {
                "following": following,
                "profile_user": user,
            }

            return render(request, "network/profile.html", context)
        else:
            new_follower = Followers.objects.create(follower=follower, user=user)
            new_follower.save()
            following = True
            context = {
                "following": following,
                "profile_user": user,
            }

            return render(request, "network/profile.html", context)


    else:
        return HttpResponseRedirect(reverse("index"))

FOLLOWING.HTML


{% extends "network/layout.html" %}

{% block body %}
    
 <div class="container">

   <div class="row justify-content-center">
            
      <div class="col-12 col-lg-8 mt-0 mt-sm-3 bg-white">
                
       <h3 class="pt-4 pb-3 text-center">Your follower's posts</h3>
           <div class="tweet-feed">
              {% for post in following_post %}
                 <div class="tweet">
                  <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
                     <div class="tweet-feed-content">
                       <div class="tweet-header">
                          <a href="{% url 'profile' user.id %}" class="tweet-author-username">{{post.user}}</a>
                              <div class="tweet-author-handle">@ {{post.user}</div>
                                <div class="tweet-dot">.</div>
                                  <div class="tweeted-time">{{post.created_at}}</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">{{post.caption}}</div>
                                    </div>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    </div>

            </div>
        </div>

    </div>
    

{% endblock %}

PROFILE.HTML

{% extends "network/layout.html" %}

{% block body %}
<div class="col-5">
    <div class="header__wrapper">
      <div class="cols__container">
        <div class="content__col">
          <div class="img__container">
            <img src="http://placeimg.com/140/140/people" alt="User image" />
            <span></span>
          </div>
            <form action="/follow" method="POST">
                {% csrf_token %}
                <h2>{{ profile_user }}</h2>
                <p>@ {{ profile_user }}</p>
                <input type="hidden" value="{{user.username}}" name="follower">
                <input type="hidden" value="{{user_object.username}}" name="user">
                {% if profile_user != request.user %}
                    {% if following %}
                        <button type="submit" class="btn btn-primary rounded-pill my-1 mx-1 py-1 py-1">Unfollow</button>
                    {% else %}
                        <button type="submit" class="btn btn-primary rounded-pill my-1 mx-1 py-1 py-1">Follow</button>
                    {% endif %}
                {% else %}
                    <a href="{% url 'logout' %}">Log Out</a>
                {% endif %}
            </form>
          <ul class="about">
            {% if following_user <= 1 %}
                <li><span>{{following_user}}</span>Follower</li>
            {% else %}
                <li><span>{{following_user}}</span>Followers</li>
            {% endif %}
            <li><span>{{followers_user}}</span>Following</li>
            {% if post_count <= 1 %}
                <li><span>{{post_count}}</span>Post</li>
            {% elif post_count >= 2 %}
                <li><span>{{post_count}}</span>Posts</li>
            {% endif %}
          </ul>

<div class="tweet-feed mt-2">
                        {% for post in profile_post %}
                            <div class="tweet">
                                <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
                                <div class="tweet-feed-content">
                                    <div class="tweet-header">
                                        <a href="#" class="tweet-author-username">{{post.user}}</a>
                                        <div class="tweet-author-handle">@ {{post.user}}</div>
                                        <div class="tweet-dot">.</div>
                                        <div class="tweeted-time">{{post.created_at}}</div>
                                    </div>
                                    <div class="tweet-content">
                                        <div class="tweet-created-content">{{post.caption}}</div>
                                    </div>
                                    <div class="engagement-icons">
                                        <ul class="engagement-icons-ul mt-1">
                                            <li><i class="fa-regular fa-comment"></i></li>
                                            <li><i class="fa-solid fa-retweet"></i></li>
                                            <li><i class="fa-regular fa-heart"></i></li>
                                            <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
      </div>
    </div>
</div>
      </div>
    </div>
</div>
{% endblock %}

URLS.PY

urlpatterns = [
    path("profile/<int:user_id>", views.profile, name="profile"),
    path("follow", views.follow, name="follow"),
]

MODELS.PY

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    pass

class NewTweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    caption = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.user} posted {self.caption}"

    class Meta: 
        # Orders posts by most recent first, by default
        ordering = ['-created_at']

class Followers(models.Model):
    follower = models.CharField(max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    # follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets')
    # target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers')

    def __str__(self):
        return self.user

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    id_user = models.IntegerField()
    bio = models.TextField(blank=True)

    def __str__(self):
        return self.user

I’m not understanding your data model here.

You have:

which I see you have commented out as being a ForeignKey to ‘User’. It really seems to me that this should be a ForeignKey - why isn’t it? (Note: I believe some of the problems are likely related to this not being an FK.)

I’ll also point out that having the Followers model being defined with the two foreign keys makes it the through table for an asymmetrical many-to-many relationship with User to itself. Since you’re defining a custom user model, it would make some operations easier to add the ManyToManyField to User. (It’s not necessary, but does make some of the relationship management functions available, allowing the code to generally be more understandable.)

What’s the purpose of the structure for your Profile model? Typically, a Profile is a OneToOne with User. Using a ForeignKey in this circumstance means that each User could have multiple Profile related to it - is that what you want?
Also, what’s the purpose behind having the id_user field? The user field is the id of the related User object.

Side note: It’s significantly better to use the ORM count method instead of using len on the queryset.

I believe that if you do some refactoring of your data models, the operations you’re looking to perform will become more clear.

1 Like

Thank you for responding.

I’ve been off the tech-grid since January so I apologize for not responding earlier, I have adjusted my code using your suggestions. Thank you

1 Like

No worries and no apologies necessary. We’re here to help.

1 Like