Django ajax跟随并取消关注

时间:2017-08-25 11:19:38

标签: python ajax django

我有一个跟随系统,它是用ajax执行的。问题是跟随按钮不起作用。它不是点击,用户编号关注者不会在一天结束时增加。我的代码如下

模板

    {% 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 %}

然后我在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'})

将根据要求提供更多代码,任何帮助都会受到关注。

1 个答案:

答案 0 :(得分:1)

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)
        })

你混淆了跟随和取消关注,当动作取消关注时,你创建联系。

模板:

{% if request.user != user %}
  <a> Follow ....
{% endif %}