django博客中的计数问题:使用django ajax [英] Counting problem in django blog: using django ajax

查看:65
本文介绍了django博客中的计数问题:使用django ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ajax为我的django博客创建了一个赞按钮,但我收到一个错误,即它的计数不正确,起初它像帖子中的0一样在我点击时起作用1就像出现了不一样的按钮但是当我击中不像又喜欢时,它会给出2个赞,有时当我不像它时显示-1,就像我认为它的jQuery问题一样,我不是jQuery的专家

jQuery

$(document).ready(function() {
  function updateText(btn, newCount, verb) {
      btn.text(newCount + " " + verb)
  }

  $(".like-btn").click(function(e) {
    e.preventDefault()
    var this_ = $(this)
    var likeUrl = this_.attr("data-href")
    var likeCount = parseInt(this_.attr("data-likes")) |0
    var addLike = likeCount + 1
    var removeLike = likeCount - 1
    if (likeUrl){
       $.ajax({
        url: likeUrl,
        method: "GET",
        data: {},
        success: function(data){
          console.log(data)
          var newLikes;
          if (data.liked){
              updateText(this_, addLike, "Unlike")
          } else {
              updateText(this_, removeLike, "Like")
              // remove one like
          }

        }, error: function(error){
          console.log(error)
          console.log("error")
        }
      })
    }
  })
})

post.html

 {% if user not in post.likes.all %}
           <p><a class='like-btn' data-href='{{ object.get_api_like_url }}'
                 data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'>
               {{ object.likes.all.count }} Like</a></p>
  {% else %}
            <p><a class='like-btn' data-href='{{ object.get_api_like_url }}'
                 data-likes='{{ object.likes.all.count }}' href='{{ object.get_like_url }}'>
                {{ object.likes.all.count }} Unlike</a></p>
  {% endif %}

views.py

class PostLikeToggle(RedirectView):

      def get_redirect_url(self, *args, **kwargs):
      obj = get_object_or_404(Post, pk=kwargs['pk'])
      url_ = obj.get_absolute_url()
      user = self.request.user
      if user.is_authenticated:
         if user in obj.likes.all():
            obj.likes.remove(user)
         else:
            obj.likes.add(user)
      return url_

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User

class PostLikeApiToggle(APIView):


    authentication_classes = [authentication.SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, pk, format=None):

        obj = get_object_or_404(Post, pk=pk)
        url_ = obj.get_absolute_url()
        user = self.request.user
        updated = False
        liked =False
        if user.is_authenticated:
           if user in obj.likes.all():
              liked = False
              obj.likes.remove(user)
           else:
               liked = True
               obj.likes.add(user)
        updated = True
        data = {
               "updated":updated,
                "liked":liked
               }

       return Response(data)

models.py

class Post(models.Model):

     title = models.CharField(max_length=200)
     author = models.ForeignKey(User,on_delete=models.CASCADE)
     likes =models.ManyToManyField(User,blank=True,related_name='post_likes')
     content = models.TextField()
     img = models.ImageField(upload_to='pics',blank=True)
     time = models.DateTimeField(default=timezone.now)

     def __str__(self):
       return self.title

    def get_absolute_url(self):
        return reverse('LoveTravel-Details', kwargs={'pk': self.pk})

    def get_like_url(self):
        return reverse('Like-Toggle', kwargs={'pk':self.pk})

   def get_api_like_url(self):
       return reverse('Like-Api-Toggle', kwargs={'pk':self.pk})

推荐答案

通过让您的API只需返回实际的新计数,就可以解决+ 2/-1问题.

The +2 / -1 problem is likely solved by having your API simply return the actual new like count.

  • 我通过翻转if(likeUrl)检查取消了javascript函数的嵌套.
  • addLike/removeLike变量被data.n_likes属性替换.
  • 由于此操作会修改服务器上的状态,因此最好将它作为POST操作发送,而不是GET.
  • I un-nested the javascript function by flipping the if(likeUrl) check.
  • The addLike/removeLike variables were replaced by the data.n_likes property.
  • Since this action modifies the state on the server, it's better to send it as a POST action than a GET.
function updateText(btn, newCount, verb) {
  btn.text(newCount + " " + verb);
}

$(document).ready(function() {
  $(".like-btn").click(function(e) {
    e.preventDefault();
    var this_ = $(this);
    var likeUrl = this_.attr("data-href");
    if (!likeUrl) return;
    $.ajax({
      url: likeUrl,
      method: "POST",
      data: {},
      success: function(data) {
        console.log(data);
        var newLikes;
        if (data.liked) {
          updateText(this_, data.n_likes, "Unlike");
        } else {
          updateText(this_, data.n_likes, "Like");
        }
      },
      error: function(error) {
        console.log(error);
        console.log("error");
      },
    });
  });
});

和后端-您不需要DRF,但是因为它已经存在-

and on the backend -- you don't need DRF for this, but since it's already there --

  • 使用def post代替def get
  • 无需检查用户是否已通过身份验证;权限类可以做到
  • 在响应中返回赞"计数(并删除不必要的updated).
  • Use def post instead of def get
  • No need to check if the user is authenticated; the permission class does that
  • Return the like count in the response (and drop the unnecessary updated).
class PostLikeApiToggle(APIView):

    authentication_classes = [authentication.SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, pk, format=None):
        obj = get_object_or_404(Post, pk=pk)
        url_ = obj.get_absolute_url()
        user = self.request.user
        liked = False
        if obj.likes.filter(id=user.id).exists():
            obj.likes.remove(user)
        else:
            obj.likes.add(user)
            liked = True

        return Response({
            "liked": liked,
            "n_likes": obj.likes.count(),
        })

希望这会有所帮助.

这篇关于django博客中的计数问题:使用django ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆