0

I need some help writing the ajax code for a like button instead of refreshing every time a like is posted. I have tried several codes but it all failed. Any recommendations on how to add a like without the page refreshing?

here is the template:

                        <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>      

Here is the urls:

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

here is the views:

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

Here is what I have tried

                        <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>

Here is the URL:

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

Here is the views:

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)
A_K
  • 283
  • 1
  • 4
  • 16

1 Answers1

0
  • 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.