当按下按钮时,Django for循环会多次激活视图

时间:2016-03-21 22:57:55

标签: javascript jquery python ajax django

我一直在博客网站上工作,当然你会发帖。我有一个index.html,我有这个:

{% for post in posts %} {% include "blog/featuredpost.html" %} {% endfor %}

我也使用了Django分页。 现在,我想要制作的是一个可以重复使用的喜欢和不喜欢的按钮,这意味着我可能想要在" blog / featuredpost.html"中使用它。所以,这就是我所做的。

<div class="row">
<div class="col-sm-5">
    <div id="divLikes" class="col-sm-6 bg-success text-center">
        Likes: {{ post.likes }}
    </div>
    <div id="divDislikes" class="col-sm-6 bg-danger text-center text-block">
        Dislikes: {{ post.dislikes }}
    </div>
</div>
{% if user.is_authenticated %}
<div>
    <div class="col-sm-2">
        <form id="like_form" action="" method="POST">
            {% csrf_token %}
            <button id="like_button" type="submit" value="vote" class="btn btn-success btn-sm btn-block">
                <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Like
            </button>
        </form>
    </div>
    <div class="col-sm-2">
        <button type="button" class="btn btn-danger btn-sm btn-block">
            <span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span> Dislike
        </button>
    </div>
    <div class="col-sm-3">
        <button type="button" class="btn btn-warning btn-sm btn-block">
            <span class="glyphicon glyphicon-comment" aria-hidden="true"></span> Comment
        </button>
    </div>
</div>
{% endif %}

 <script type="text/javascript">
       //$('#like_button').click(function(){ }); 
/* The for cycle sends all the posts id that should appear on the page. 
It should send just the one on which the like button is clicked. */
$(document).on('submit', '#like_form', function(event) {
event.preventDefault();
$.ajaxSettings.traditional = true;
$.ajax({
    type: 'POST',
    url: '{% url "like" %}',
    dataType: 'json',
    data: {
        csrfmiddlewaretoken: '{{ csrf_token }}',
        LikeId: {{ post.id }},
    },
    success: function(response) {
        $('#divLikes').load(' #divLikes', function() { 
            /* It's important to add the space before #divLikes, I don't know why */
            $(this).children().unwrap()
        })
    }
});

})

views.py

def view_like(request):
# AJAX Like Button
if request.user.is_authenticated:
    if request.method == 'POST':
        likepostId = request.POST.get('LikeId', '')
        print(likepostId)
        likepost = get_object_or_404(Post, id=likepostId)

        print(likepost.title + " has " + str(likepost.likes))

        response_data = {}
        return JsonResponse(response_data)
else: 
    raise Http404

return 200

我目前拥有它所以它会打印出某些东西。在首页上,由于AJAX成功功能,它实际上只是复制了html / css部分。如何让“喜欢”按钮明确知道我想要点击我点击的某个帖子?因为,就像现在一样,它只是阻止页面上所有其他帖子的所有ID,没有特别的顺序。

1 个答案:

答案 0 :(得分:0)

问题是你有一堆具有相同id(#like_form#like_button)的节点,并且你向所有节点添加了事件。不允许多个元素具有相同的id值。 从id移除属性form,将button&#39; s id更改为class,并将其值设置为帖子的ID,即:

<button type="submit" value="{{ post.id }}" class="vote_button btn btn-success btn-sm btn-block">

然后将事件挂钩到班级.vote_button,并提交其值(以便data.LikeId请求中的ajax类似于$(event.target).val())以识别哪个帖子你投了一票

编辑:

javascript大致如下:

<script type="text/javascript">
$(".vote_button").click(function(event) {
    event.preventDefault();
    $.ajaxSettings.traditional = true;
    $.ajax({
        type: 'POST',
        url: '{% url "like" %}',
        dataType: 'json',
        data: {
            csrfmiddlewaretoken: '{{ csrf_token }}',
            LikeId: $(event.target).val(),
        },
        success: function(response) {
            /* I am not sure what is this supposed to do
               load() expects url as the first parameter, not a node
            */
            $('#divLikes').load('#divLikes', function() { 
                $(this).children().unwrap()
            })
        }
    });
});
</script>
相关问题