0

I am creating a follower system and an unfollow system using django. I have implemented every code and there seems to be no error except from the fact that instead of the initial button to be follow it is actually unfollow and if I click on unfollow nothing happens. below is my code

details.html

{% extends 'base.html' %}
{% load staticfiles %}
{% load thumbnail %}
{% block title %}{{ user.get_full_name }}{% endblock %}
{% block content %}
<h1>{{ user.get_full_name }}</h1> <div class="profile-info">
{% thumbnail user.profile.photo "180x180" crop="100%" as im %} <img src="{{ im.url }}" class="user-detail">
{% endthumbnail %} </div>
{% with total_followers=user.followers.count %} <span class="count">
<span class="total">{{ total_followers }}</span>
follower{{ total_followers|pluralize }} </span>
<a href="#" data-id="{{ user.id }}" data-action="{% if request.user in user.followers.all %}un{% endif %}follow" class="follow button">
 {% if request.user not in user.followers.all %}
 Follow
 {% else %}
 Unfollow
  {% endif %}
</a>
<div  id="post-list" class="image-container">
{% include "axle.html" with objects=user.posts_created.all %}
</div>
{% endwith %}
{% endblock %}

  {% block domready %}
  $('a.follow').click(function(e){
    e.preventDefault();
    $.post('{% url "user_follow" %}',
    {
      id: $(this).data('id'), action: $(this).data('action')
    }, function(data){
          if (data['status'] == 'ok') {
            var previous_action = $('a.follow').data('action');
            // toggle data-action $('a.follow').data('action',
            previous_action == 'follow' ? 'unfollow' : 'follow'); // toggle link text
    $('a.follow').text(
         previous_action == 'follow' ? 'Unfollow' : 'Follow');
    // update total followers
    var previous_followers = parseInt(
    $('span.count .total').text());
    $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1);
    } }
    ); });
  {% endblock %}

views.py

def user_detail(request, username):
    user = get_object_or_404(User, username=username,is_active=True)
    context = {
        'section': 'people',
        'user': user
    }
    template = 'user/detail.html'
    return render(request, template, context)

model

class Contact(models.Model):
    """docstring for Contact."""
    user_from = models.ForeignKey(User, related_name='rel_from_set')
    user_to = models.ForeignKey(User, related_name='rel_to_set')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return    '{} follows {}'.format(self.user_from, self.user_to)

models.ManyToManyField('self', through=Contact,related_name='followers', symmetrical=False)

maybe the Monkey patch of the ManyToManyField?

Herberth Amaral
  • 3,479
  • 3
  • 33
  • 35
King
  • 1,885
  • 3
  • 27
  • 84
  • What user model are you using? Django's default? I suggest you to override the django's user model (how to: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-the-existing-user-model)and implement your contact relationship in there. Also, that model patch seems totally awkward to me. Better put it inside the model. – Herberth Amaral Aug 24 '17 at 18:03
  • please show your User model as well. – Umar Asghar Aug 24 '17 at 18:23
  • I am using django all-auth as my authentication and using django's default user model – King Aug 24 '17 at 18:24
  • @HerberthAmaral can you please explain how I could go about it? – King Aug 24 '17 at 18:25
  • it still does not work. just shows unfollow by default – King Aug 24 '17 at 18:33
  • @HerberthAmaral how to I achieve what you suggested? – King Aug 24 '17 at 19:04
  • @King it seems your problem is solved now. Please, ping me again if I'm mistaken. – Herberth Amaral Aug 25 '17 at 19:14
  • @HerberthAmaral I do actually. Kindly check this link for me. it is a different question but same system. https://stackoverflow.com/questions/45880197/django-ajax-follow-and-unfollow?noredirect=1#comment78726534_45880197 – King Aug 25 '17 at 19:18

1 Answers1

0

You condition is wrong. You are checking if current logged in (session) user in user (which was filtered as a query by username) followers list.

Instead It used be if searched or query user is in the followers of the current logged in user followers list.

Then it should work and it should show you Follow instead of UnFollow.

Or search this way, get list user_from Contact table where from is current logged in user and user_to is querying user in you detail view.

Or In your details view. Search the queried user in logged in user follower list. Put the flag in it. Use that flag in the template to toggle either Follow or UnFollow.

follow_flag = False
query_set = request.user.followers_set.filter(username=user.username)
if query_set.exists():
    follow_flag = True

use that flag in your template.

Umar Asghar
  • 3,808
  • 1
  • 36
  • 32
  • by default it is supposed to count 0 followers `{% with total_followers=user.followers.count %} ` but it does not show 0 followers on the screen – King Aug 24 '17 at 18:38
  • it shows how much followers by default? please tell me about it. – Umar Asghar Aug 24 '17 at 18:40
  • yes by default it is supposed to show 0 followers since no one has followed that particular user – King Aug 24 '17 at 18:41
  • I think I figued the question but I dont Know how to solve it. This extra column to the user table is not getting added `# Add following field to User dynamically User.add_to_class('following', models.ManyToManyField('self', through=Contact,related_name='followers', symmetrical=False) ` – King Aug 24 '17 at 19:03