在Django中的Alike按钮中添加Ajax

我需要一些帮助来为alike按钮编写ajax代码,而不是每次发布alike时都刷新。我尝试了几个代码,但都失败了。关于如何在不刷新页面的情况下添加“赞”的任何建议?

这是模板:

                        <form action="{% url 'score:like_post' post.pk %}" method='POST'>
                            {% csrf_token %}
                    {% if user.is_authenticated %}
                            {% if liked %}
                                <button type='submit' name='post_id' class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike </button>                            
                            {% else %}
                                <button type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>                            
                            {% endif  %}
                    {% else %}
                    <small><a href="{% url 'login' %}"> Login</a> to Like </small>
                    {% endif %}
                            <strong>{{total_likes}} Likes </strong>                    
                        </form>      

这是网址:

    path('like/<int:pk>', LikeView, name='like_post'),

这里是意见:

def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    like = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        like = False

    else:
        post.likes.add(request.user)
        like = True
    return redirect('score:post-detail', pk=pk)

class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()

        stuff = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = stuff.total_likes()

        liked = False
        if stuff.likes.filter(id=self.request.user.id).exists():
            liked = True

        context["total_likes"] = total_likes
        context["liked"] = liked
        return context

这是我尝试过的

                        <form action="{% url 'score:like_post' post.pk %}" method='POST'>
                            {% csrf_token %}
                    {% if user.is_authenticated %}
                            {% if liked %}
                                <button type='submit' name='post_id' class= "btn btn-danger btn-sm" Onclick="Onclick()" value="{{post.id}}"> Unlike </button>                            
                            {% else %}
                                <button type='submit' name='post_id' class= "btn btn-primary btn-sm" Onclick="Onclick()" value="{{post.id}}"> Like </button>                            
                            {% endif  %}
                    {% else %}
                    <small><a href="{% url 'login' %}"> Login</a> to Like </small>
                    {% endif %}
                            <strong>{{total_likes}} Likes </strong>                    
                        </form> 
                        <input id= "post_id" type= "hidden" name="name" value= "{object.id}">

<script>
    function Onclick(){
        var i=document.getElementById(‘post_id’).value
        $.ajax({
            url:”/ajax/likes/”,
            data:{‘i’:i},
            datatype:’json’
            success:function(data){
            document.getElementById(‘like’).innerHTML=data.i
            }
        })
    }
</script>

这是网址:

path('ajax/like/<int:pk>', LikeView, name='like_post'),

这里是视图:

def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    like = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        like = False

    else:
        post.likes.add(request.user)
        like = True
    return redirect('score:post-detail', pk=pk)
评论
  • Kennedy
    Kennedy 回复
    • This answer will help. https://stackoverflow.com/a/6960586/13499618.
    • You basically want to don't want the default behaviour i.e, form submit and page refresh, but you want an Ajax submission.
    • You implement it in django just like you would implement it pure html, as in the end django templates render out to become pure html files.