如何在Django中为喜欢按钮使用Ajax

时间:2020-07-04 07:36:12

标签: python jquery django ajax django-views

我想为我的博客中的“喜欢”按钮提供Ajax功能。我首先实现了类似功能,它按预期工作(单击类似按钮后重新加载页面)。然后,我要实现Ajax,以便在单击类似按钮后不应该重新加载页面。但是,它没有按预期工作。

views.py:

def like_post(request):
    user = request.user
    if request.method == 'POST':
        post_id = request.POST.get('id')
        post_obj = get_object_or_404(Post, id=post_id)

        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
        else:
            post_obj.liked.add(user)

        like, created = Like.objects.get_or_create(user=user, post_id=post_id)

        if not created:
            if like.value == 'Like':
                like.value = 'Unlike'
            else:
                like.value = 'Like'

        like.save()
    if request.is_ajax():
        post = Post.objects.all()
        context={
        'post': post
        }
        html = render_to_string('blog/like_section.html', context, request=request)
        return JsonResponse({'form': html})

base.html中的jQuery

<script src="https://code.jquery.com/jquery-3.1.1.min.js">
    <script type="text/javascript">
        $(document).ready(function(event){
            $(document).on('click', '#like', function(event){
                event.preventDefault();
                console.log("hello")
                var pk = $(this).attr('value');
                $.ajax({
                    type : 'POST',
                    url : {% url 'like-post' %},
                    data : {'id' : pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, 
                    dataType : 'json',
                    success : function(response){
                        $('#like-section').html(response['form'])
                        console.log($('#like-section').html(response['form']));
                    },
                    error : function(rs, e){
                        console.log(rs.responseText);
                    },
                });
            });
        });
    </script>

like_section.html:

<form action="{% url 'like-post' %}" method="POST">
      {% csrf_token %}
      <input type="hidden" name="post_id" value="{{ post.id }}">
      {% if user not in post.liked.all %}
        <button id="like" class="btn btn-outline-info mb-4" type="submit">Like</button>
      {% else %}
        <button id="like" class="btn btn-info mb-4" type="submit">Unlike</button>
      {% endif %}
</form>

urls.py:

path('likes/', views.like_post, name='like-post'),

它返回404,且没有帖子与给定查询匹配。我的观察是,它似乎没有检测到Jquery部分,因为如果我将'id'的{​​{1}}和'post_id'中的request.POST.get('id')替换为return redirect,它的工作原理就像以前的版本(如果我按赞按钮,则重新加载页面)。因此控件永远不会进入request.method == 'POST'循环,如何使Django使用Ajax?

0 个答案:

没有答案