1

I have a follower system in place and it is executed with ajax. The problem is the follower button doesnt work. it is not clicking and user number followers does not increase at the end of the day. I have my codes below

template

    {% with objects=user.followers.count %}
      <span class="count">
      <span class="total">
        {{ objects }}
      </span>
        follower{{ objects|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>

{% block query %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script>
<script>
var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken);
} }
});
$(document).ready(function(){
  $('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);
    } }
    ); });
}); </script>

{% endblock %}

then I supplied block query in my base.html

Views.py

def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = User.objects.get(id=user_id)
            if action == 'unfollow':
                Contact.objects.get_or_create( user_from=request.user, user_to=user)
            else:
                Contact.objects.filter(user_from=request.user,user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except User.DoesNotExist:
            return JsonResponse({'status':'ko'})
    return JsonResponse({'status':'ko'})

further codes would be supplied on request any help would be loved.

King
  • 1,885
  • 3
  • 27
  • 84

1 Answers1

2
def user_follow(request):
    user_id = request.POST.get('id', None)
    action = request.POST.get('action', '')

    FOLLOW_ACTION = 'follow'
    UNFOLLOW_ACTION = 'unfollow'

    if request.user.is_anonymous:
        return JsonResponse({
            'status':'ko',
            'message': 'You must login'}
        )

    if action not in [FOLLOW_ACTION, UNFOLLOW_ACTION]:
        return JsonResponse({
            'status':'ko',
            'message': 'Unknown action {}'.format(action)}
        )

    try:
        user = User.objects.get(id=user_id)
        if action == UNFOLLOW_ACTION:
            Contact.objects.filter(user_from=request.user,user_to=user).delete()
            return JsonResponse({
                'status':'ok'
                })
        else:
            contact, created = Contact.objects.get_or_create( user_from=request.user, user_to=user)
            return JsonResponse({
                'status':'ok',
                'message': 'Following id : {}'.format(contact.id)
            })


    except User.DoesNotExist:
        return JsonResponse({
            'status':'ko'
            'message': 'user id: does not exist: {}'.format(user_id)
        })

You mixed up follow and unfollow, when action is unfollow you create contact.

Template:

{% if request.user != user %}
  <a> Follow ....
{% endif %}
user2021091
  • 561
  • 2
  • 11
  • Hard to tell, check on your browser using f12 – user2021091 Aug 28 '17 at 15:04
  • I have implemented it but the follow button is not getting clicked and `'message': 'user id: does not exist: {}'.format(user_id)` keeps given invalid index – King Aug 28 '17 at 15:05
  • error in terminal `'message': 'Following id : {}'.format(contact.id) AttributeError: 'tuple' object has no attribute 'id'` – King Aug 28 '17 at 15:06
  • fixed. I can not appreciate you enough. Thank you – King Aug 28 '17 at 15:11
  • I think it is werid that users can actually follow themselves I expected the follow button to be hidden based on my code – King Aug 28 '17 at 15:12
  • Sorry for the attributeError I fixed it in the code and wrote down the template to hide the button – user2021091 Aug 28 '17 at 15:22
  • Hi @uswe2021091 I need you help regarding a question. https://stackoverflow.com/questions/46263867/creating-relationship-between-two-apps-in-django – King Sep 18 '17 at 10:04
  • Hi. kindly help check this question. I dont know why the like button does not function well and the same error occurs to the follow button https://stackoverflow.com/questions/48229930/django-like-button-counting-irregularly – King Jan 12 '18 at 16:23