我如何将django like按钮连接到ajax以自动刷新

时间:2019-06-24 02:49:22

标签: javascript django ajax

我有一个正在处理的django项目。用户可以喜欢和不喜欢该帖子。

models.py

class Tweet(models.Model):
    tweet_user = models.ForeignKey(User, on_delete=models.CASCADE)
    tweet_message = models.TextField()
    tweet_date = models.DateTimeField(auto_now_add=True)
    tweet_like_counter = models.IntegerField(default=0)
    tweet_picture = models.FileField(null=True,blank=True)
    def __str__(self):
        return self.tweet_message


class Like(models.Model):
    user = models.ManyToManyField(User)
    tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.tweet.tweet_message

class Disike(models.Model):
    user = models.ManyToManyField(User)
    tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.tweet.tweet_message

views.py

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
@login_required
def like(request, pk):
    currentTweet = get_object_or_404(Tweet,pk=pk)
    username = User.objects.get(pk=request.user.id)
    like_queryset = Like.objects.filter(tweet=currentTweet, user=username)
    dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username)


    if like_queryset.exists():
        Like.objects.filter(tweet=currentTweet, user=username).delete()
        dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
        likeobject = Like.objects.filter(tweet=currentTweet).count()
        currentTweet.tweet_like_counter = likeobject - dislikeobject
        currentTweet.save()

    if dislike_queryset.exists():
        Disike.objects.filter(tweet=currentTweet, user=username).delete()
        dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
        likeobject = Like.objects.filter(tweet=currentTweet).count()
        currentTweet.tweet_like_counter = likeobject - dislikeobject
        currentTweet.save()


    like = Like.objects.create(tweet=currentTweet)
    like.user.add(username)
    dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
    likeobject = Like.objects.filter(tweet=currentTweet).count()
    currentTweet.tweet_like_counter = likeobject - dislikeobject
    currentTweet.save()

    return JsonResponse({
        'like_counter': currentTweet.tweet_like_counter
    })


@csrf_exempt
@login_required
def dislike(request, pk):
    currentTweet = get_object_or_404(Tweet, pk=pk)
    username = User.objects.get(pk=request.user.id)
    like_queryset = Like.objects.filter(tweet=currentTweet, user=username)
    dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=username)

    if dislike_queryset.exists():
        Disike.objects.filter(tweet=currentTweet, user=username).delete()
        dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
        likeobject = Like.objects.filter(tweet=currentTweet).count()
        currentTweet.tweet_like_counter = likeobject - dislikeobject
        currentTweet.save()

    if like_queryset.exists():
        Like.objects.filter(tweet=currentTweet, user=username).delete()
        dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
        likeobject = Like.objects.filter(tweet=currentTweet).count()
        currentTweet.tweet_like_counter = likeobject - dislikeobject
        currentTweet.save()

    dislike = Disike.objects.create(tweet=currentTweet)
    dislike.user.add(username)
    dislikeobject = Disike.objects.filter(tweet=currentTweet).count()
    likeobject = Like.objects.filter(tweet=currentTweet).count()
    currentTweet.tweet_like_counter = likeobject - dislikeobject
    currentTweet.save()

    return JsonResponse({
        'like_counter':  currentTweet.tweet_like_counter

    })

模板

 <p class='id{{ post.tweet_user }}' name="tweetlikes" class="card-text" style="background-color: lightgray;"><strong>{{ post.tweet_like_counter }} likes </strong></p>

<form   id="like{{ post.tweet_user }}" method="POST" name="likeform" action="{% url 'like' pk=post.pk %}"   style="float:left;">
          {% csrf_token %}
        <button type="submit" class="like-form" name="like" class="btn btn-primary" >Like</button>
</form>

<script>
       $('#like{{ post.tweet_user }}').on('submit', function(event){
           event.preventDefault();
                             var oldVal =  parseInt($(".id{{ post.tweet_user }}").text())
        var url = $('#like{{ post.tweet_user }}').attr('action');

        $.ajax({
            type: 'POST',
            url:url,
            data:{
                'like_counter':oldVal
            },
            dataType: 'json',
            success:function(data){
                $(".id{{ post.tweet_user }}").html(data.like_counter + " " +  "likes");
            }
        })
    })
</script>

<form   id="dislike{{ post.tweet_user }}" name="dislikeform" method="POST" action="{% url 'dislike' pk=post.pk %}" style="float:right;" >
          {% csrf_token %}
    <button type="submit"  class="btn btn-primary">Dislike</button>
</form>

<script>
   $('#dislike{{ post.tweet_user }}').on('submit', function(e){
           e.preventDefault();
                             var oldVal =  parseInt($(".id{{ post.tweet_user }}").text())
        var url = $('#dislike{{ post.tweet_user }}').attr('action');

        $.ajax({
            type: 'POST',
            url:url,
            data:{
                'like_counter':oldVal
            },
            dataType: 'json',
            success:function(data){
                $(".id{{ post.tweet_user }}").html(data.like_counter + " " +  "likes");
            }
        })
    })
</script>
</div>

问题出在我的ajax。我的网站的功能很棒。它只是ajax。当用户单击第一条帖子上的“喜欢”按钮时,它仅允许用户一次喜欢该按钮。当另一个用户发布一个帖子(在页面上发布两个帖子)时,像按钮这样的按钮发布不再起作用,并且它更改了类似的数字标签,并且还使数据变得不同。请帮忙吗?

1 个答案:

答案 0 :(得分:0)

为什么用户使用ManyToManyField链接到喜欢/不喜欢?用户之间可以共享一个“喜欢”吗? ForeignKey在这里可以正常工作。

此外,由于您的代码声明用户不能同时在同一“ tweet”上同时拥有LikeDislike,因此建议您使用{{ 1}}或数字字段,表示Boolean+1

您可以使用-1F()Subquery()表达式或Count/Sum聚合来代替使用那么多查询来破坏数据库。后者还将解决更新查询中的竞争条件问题。

[update_or_create][1]

如果第一条语句存在带有user_id和tweet_id的Like对象,则将创建或更新。请注意,def like(request, pk): Like.objects.update_or_create(tweet_id=pk, user=request.user, defaults={"value": <+1/-1>}) Tweet.objects.filter(pk=pk, ).annotate(likes_count=Sum(tweet__like__value), ).\ update(tweet_like_counter=F(likes_count), ) like_counter = Tweet.objects.values_list('tweet_like_counter', flat=True).get(pk=pk,) return JsonResponse({ 'like_counter': like_counter }) 对象中已经存在user值,因此您无需进行其他查询即可实现该值。 同样,您也不需要使用给定的tweet_id(等于request arg)实例化Tweet对象-此处的pk / tweer_id就足够了。

下一条语句将基于所有存在的喜欢/不喜欢的汇总来更新pk。此更新将在代码中执行一个SQL命令,而不是4个命令:获取Tweet对象,获取两个计数器,使用新计数器保存Tweet对象。

声明三将检索当前的tweet_like_counter。请注意,它选择a single column而不是实例化完整的like_counter对象。