django像按钮计数不规则

时间:2018-01-12 16:05:22

标签: jquery django

我有一个django应用程序,我为博客上发布的帖子实现了一个类似的按钮。我最近发现,当注册用户点击类似按钮时,类似的增加非常多。而不是增加1的喜欢的数量,它增加了90+,当点击按钮时,它会改变为不同,它仍然增加,所以类似的功能变得不均匀。下面是我的类似函数的代码

Html

{% with total_likes=obj.likes.count likes=obj.likes.all %}
      <span class="count">
      <span class="total">{{ total_likes }}</span>
        like{{ total_likes|pluralize }} </span>
      <a href="#" data-id="{{ obj.id }}" data-action="{% if request.user in likes %}un{% endif %}like" class="like button">

               {% if request.user not in users_like %}
               like
                {% else %}
                unlike
                {% endif %}
      </a>

JQuery的

<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.like').click(function(e){
  e.preventDefault();
$.post('{% url "posts:like" %}',
  {
    id: $(this).data('id'),
    action: $(this).data('action')
  }, function(data){
    if (data['status'] == 'ok') {
      var previous_action = $('a.like').data('action');
  // toggle data-action
  $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like');
  // toggle link text
  $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like');
  // update total likes
var previous_likes = parseInt($('span.count .total').text());
  $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1);
    } }
); });

  });
  </script>

视图

def post_likes(request):
    post_id = request.POST.get('id')
    action = request.POST.get('action')
    if post_id and action:
        try:
            instance = Post.objects.get(id=post_id)
            if action == 'like':
                instance.likes.add(request.user)
            else:
                instance.likes.remove(request.user)
            return JsonResponse({'status': 'ok'})
        except:
            pass
    return JsonResponse({'status': 'ko'})

模型

likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='post_likes')

我也试过通过cdn <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>使用这个jquery,但它根本不会使like按钮工作。

0 个答案:

没有答案