Home > Enterprise >  Django json response stay in the same page
Django json response stay in the same page

Time:12-04

I'm making a like button for a post in django. What I need is that when the like button is clicked, the function is executed, but I need the page not to be reloaded (To later use javascript). To do that I return a jsonresponse() instead of a return render. But the real problem is that it redirects me to the page that I show in the photo. The page is not reloaded. as I want it. but I don't want it to show me the blank page with the jsonresponse data (like this photo).I want to stay in the same page without reload.

What I get

My view function:

def liking (request, pk):

posts = get_object_or_404(Post, id = pk)
if request.user in posts.likes.all():
    posts.likes.remove(request.user)
else:    
    posts.likes.add(request.user.id)
    
    
likes_count = posts.likes.all().count()
print(f'likes_count = {likes_count}')
data= {
    'likes_count': likes_count,
}
#return redirect ('index')# This is commented


return JsonResponse(data, safe=False, status=200 )

CodePudding user response:

You can use AJAX. Simply place the code below in the template and trigger it with buttons.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
    function get_likes(pk){
        $.ajax({
            url: '{% url "url-name" pk %}',
            type: 'GET',
            success: function (res) {
                var likes = JSON.parse(res);
                return likes["likes_count"]
            }
        });
    }
</script>

If you need to post any data, you can use the lines below.

function get_likes(pk){
    $.ajax({
        url: '{% url "url-name" pk %}',
        type: 'POST',
        data: { 
            csrfmiddlewaretoken: "{{ csrf_token }}",
            data1:"data",
            data2:"data"
        },
        success: function (res) {
            var likes = JSON.parse(res);
            return likes["likes_count"]
        }
    });
}

You can add the following lines in your function to use the posted data on the django side.

data1 = request.POST.get("data1")
data2 = request.POST.get("data2")

CodePudding user response:

After trying for a while, I found the problem. It had nothing to do with the ajax request or a fetch, which is what I ended up using. It was simply that I had the url of the views.py function in the href="" and for this reason the white screen came out with the jsonresponse() data:

I had to change:

<a  id="like_button" href="{% url 'liking'  post.id %}"> Like</a>

So:

<a  id="like_button" href="#"> Like</a>

Thanks for all the answers!

  • Related