【问题标题】:how to increment a like button in django with ajax?如何使用ajax在django中增加一个like按钮?
【发布时间】:2021-02-11 06:35:34
【问题描述】:

我在社区中有一个帖子,我已经在 django + ajax 中实现了点赞按钮,但我注意到当我喜欢一个帖子时,它会增加所有帖子的点赞数。我该如何解决? 这是我的模板:

{% for post in posts %}
          <div class="w3-container w3-card w3-white w3-round">
        <a target="_blank" href="{{ post.author.profile.avatar.url }}">
        <img src="{{ post.author.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"></a>
        <h4>
        <a href ='{% url 'profile' post.author.pk %}'>{{ post.author.profile.prenom|title }} {{ post.author.profile.nom|title }}</a>
        </h4>
        <span class="w3-opacity">{{ post.created|date:"d-m-Y H:i" }}</span>
         <br>
        <hr class="w3-clear">
        <p>
    {{ post.contenu }}</p>
           <button type="button" class="btn btn-default btn-sm">
          {{ post.comment_set.count }}  <a href='#'><span class="glyphicon glyphicon-comment"></span> </a>
        </button>
    {% if request.user in post.liked.all %}
        <button type="button" class="btn btn-default btn-sm">
              <span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: blue;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
    </button>
    {% else %}
    <button type="button" class="btn btn-default btn-sm">
           <span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: black;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
    </button>
    {% endif %}
    {% if request.user == post.author %}
               <button type="button" class="btn btn-default btn-sm">
          <a href='{% url 'delete' post.id community.id %}'><span class="glyphicon glyphicon-trash"></span> </a>
        </button>
    {% endif %}
    <br>
    <br>
    </div>
    <br>
    {% empty %}
    <span class='w3-opacity'>Aucun post dans cette communaute</span>
    <br>
    <br>
 {% endfor %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// AJAX CALL
$('.likin').click(function(){
    $.ajax({
             type: "POST",
             url: "{% url 'like_community' %}",
             data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
             dataType: "json",
             success: function(response) {
              selector = document.getElementsByName(response.content_id);
                    if(response.liked==true){
                      $(selector).css("color","blue");
                      $('.like_count').html(response.likes_count);
                    }
                    else if(response.liked==false){
                      $(selector).css("color","black");
                      $('.like_count').html(response.likes_count);
                    }


              }

        });

  })
</script>

这是我的views.py,部分ajax如下:

def like_community(request):
    if request.method =="POST":
        if request.POST.get("operation") == "like_submit" and request.is_ajax():
            content_id=request.POST.get("content_id",None)
            content=get_object_or_404(Post,pk=content_id)
            if content.liked.filter(id=request.user.id): #already liked the content
                content.liked.remove(request.user) #remove user from likes
                liked=False
            else:
                content.liked.add(request.user)
                liked=True
            ctx={"likes_count":content.liked.count() ,"liked":liked,"content_id":content_id}
            return HttpResponse(json.dumps(ctx), content_type='application/json')

我真的需要帮助。我是 ajax 新手,我只是在网上找到了一个教程,然后我就跟着学习了,但是 count_like 按钮的实现不存在。我将不胜感激。谢谢。

【问题讨论】:

    标签: javascript jquery django ajax


    【解决方案1】:

    您的 ID 似乎不是唯一的“co” - 然后您使用了错误的方法 document.getElementsByName,它返回了一个 NAMED 元素的集合,但您传递了它 response.content_id

    你也可以使用$('#response.content_id'),它会寻找一个带有`id="response.content_id"的元素

    改成

    $('.likin').click(function(e){
      e.preventDefault; // stop the link 
      $liked = $(this); // the link clicked
      $.ajax({
        success: function(response) {
           $liked.prev().html(response.likes_count); // the span before the "likin"
           $liked.css("color",response.liked==true ? "blue": "black");
        }
    

    【讨论】:

    • 非常感谢,它让我度过了愉快的一天。能否请你给我一个学习 ajax 的好链接,因为我也面临一个问题,因为我在重新加载页面以显示新消息用户到 -我的应用程序中的用户我知道我应该在 javascript 中使用 ajax 和 setinterval() 但我不知道如何?再次感谢。
    • 永远不要在 Ajax 中使用 setInterval。只需在成功中使用 setTimeout
    • 没有。您创建了一个加载数据的函数,并在成功或完成时,将 setTimeout 添加到同一个函数中,时间为 60000 毫秒,因此它将在一分钟内再次调用,依此类推
    • 谢谢,我会试试的。你真是个了不起的好人。
    • 类似function loadPage() { $.ajax..... success: function() { setTimeout(loadPage,60000); }, ...}); }; $(function() { loadPage() });
    猜你喜欢
    • 2021-05-30
    • 1970-01-01
    • 2017-08-24
    • 2021-05-29
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多