how to write Ajax for a Like button in Django

248 views
Skip to first unread message

Ahmed Khairy

unread,
May 18, 2020, 12:15:06 AM5/18/20
to Django users
Hi all,

I need some help writing the ajax for a like button instead of refreshing every time a like is posted 

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>
                            <strong>{{total_likes}} Likes </strong>
                    {% endif %}
                        </form>     

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

here is the views:
def LikeView(requestpk):
    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



Gabriel Araya Garcia

unread,
May 18, 2020, 12:27:42 AM5/18/20
to django...@googlegroups.com
Hi Ahmed, I was looking for that during several months and I have found examples than not run, and therefore I`ve get one conclution: "It`s not posible to get that functionality in Django". No one could demostrate with example code.
If you find something, please send me the code.

Thanks

  
Gabriel Araya Garcia
GMI - Desarrollo de Sistemas Informáticos




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/00707977-9b68-4329-a13d-adb9ab7b8813%40googlegroups.com.

Motaz Hejaze

unread,
May 18, 2020, 1:30:38 AM5/18/20
to Django users
In your like button form in your templates , 
try this :

<form onsubmit="return false">
</form>

i don't think you need ajax for this , but if you still need it let us know

Ahmed Khairy

unread,
May 18, 2020, 1:53:09 AM5/18/20
to Django users
Hi Motaz,

When I added your code it disabled the function of the button nothing happened
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

Motaz Hejaze

unread,
May 18, 2020, 2:05:12 AM5/18/20
to Django users
The button is submitted but without page refresh

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/76f6356b-17bc-4697-b6cf-966f01e9217f%40googlegroups.com.

Vishesh Mangla

unread,
May 18, 2020, 11:50:23 AM5/18/20
to django...@googlegroups.com

Why don’t you use fetch api? Its simple. Once you get the response from the server, you can use InsertAdjacentHtml.

 

Sent from Mail for Windows 10

Ahmed Khairy

unread,
May 18, 2020, 10:18:05 PM5/18/20
to Django users
Hi Motaz,

I tried it again now but when I press it there is no change. The likes count is the same and the like button doesnt change to dislike
Reply all
Reply to author
Forward
0 new messages