mardi 28 juin 2016

Can not change number of likes for post in tape with ajax, when click like button


I am trying to learn django and a bit more. Got a problem with counting number of likes for every post in tape. Problem is that I can not get id of post. If I refresh page, count of likes changes. But to make it changing with ajax is real problem. Please explain me how make changing likes count for every post in tape, if click like button.

Ajax code.

{% block jquery %}
    function updatePostLikesCount(){
        var postlikescount = $(".post-likes-count");
        var count = $(this)
        $.ajax({
            type: "GET",
            """Here is the biggest problem for me"""
            url: "/like_post/{{ post.id }}/post_likes_count/",
            success: function(data){
                postlikescount.html(data.count);
            },
            error: function(response, error){
            }
        })
    }
    updatePostLikesCount();

    $(".post-like").click(function(event){
        var img = $(this);
        event.preventDefault();
        $.ajax({
            url: img.parent().attr('href'),
            success: function(){
                updatePostLikesCount();
            },
            error: function(response, error){
            }
        })
    });
{% endblock %}

Here is tape of posts.

{% for post in tape %}
    ...
    {{ post.text }}
    ...
    <a class="post-like-href" href="/like_post/{{ post.id }}/">
        <img class="post-like"  src="{% static "" %}"/>
    </a>
    {% if post.like.liked_users.count > 0 %}
            <span class="post-likes-count" >
                {{ post.like.liked_users.count }}
            </span>
    {% endif %}
{% endfor %}

Here is a view that count post's likes

def post_likes_count(request, post_id, *args, **kwargs):
    if request.is_ajax():
        like = Like.objects.get(post_id=post_id)
        if like.liked_users.count == None:
            count = 0
        else:
            # like = Like.objects.get(post_id=post_id)
            count = like.liked_users.count()
        return JsonResponse({
            'count': count,
        })
    else:
        raise Http404

Else I tried to reload an element of page with likes , but was defeated :-)


Aucun commentaire:

Enregistrer un commentaire