Мой ajax-запрос в django перенаправляет на другую страницу, содержащую данные ответа после отправки

после отправки ajax запроса, он перенаправляет меня на другую пустую страницу, содержащую мои возвращенные данные. Я хотел, чтобы после отправки формы она оставалась на той же странице.

вот мое мнение

VIEWS.PY

def LikePost(request,pk,slug):
    model=Post
    post=Post.objects.get(pk=pk,slug=slug)
        #if request.is_ajax():
    is_like=False
        
    for like in post.post_likes.all():
        if like == request.user:
            is_like=True
            break
    
    if not is_like:
        post.post_likes.add(request.user)
            
    if is_like:
        post.post_likes.remove(request.user)
    notify=Notification.objects.create(notification_type='LP',user=post.publisher,sender=request.user,text_preview=" some one liked your  post")
    notify.save()
    likes_count=post.post_likes.count()
    data={
        'likes_count':likes_count,
            }
        
    return HttpResponse(json.dumps(data),content_type='application/json' )

и моя форма

     <form method="POST" class="likeForm" action="{% url 'like-post' post.id post.slug %}" >
         {% csrf_token %}
         <input type="hidden" value="{{ request.path }}" name="next">

<button type='submit'>like</button>

и мой вызов ajax

$.each('.likeForm').on('submit', function(event){
    event.preventDefault();
    event.stopPropagation();
    $.ajax({
        type:'POST',
        url:$('.likeForm').attr('action'),
        data:{
            csrfmiddlewaretoken:"{{ csrf_token }}",
        datatype:'json',
        cache:false,
        async:true,
        },
        success:function(data){
           
            $.each('.counter').text(data.likes_count)
        },
        failure: function(){
            
        }
    })
    return false
})

продолжает перенаправлять на пустую страницу

любая помощь для этого?

Вам нужно вернуть JSON-ответ, а не HTTP-ответ.

from django.http import JsonResponse


def LikePost(request, pk, slug):
    model=Post
    post=Post.objects.get(pk=pk, slug=slug)
        #if request.is_ajax():
    is_like=False
        
    for like in post.post_likes.all():
        if like == request.user:
            is_like=True
            break
    
    if not is_like:
        post.post_likes.add(request.user)
            
    if is_like:
        post.post_likes.remove(request.user)
    notify=Notification.objects.create(notification_type='LP',user=post.publisher,sender=request.user,text_preview=" some one liked your  post")
    notify.save()
    likes_count=post.post_likes.count()
    data={
        'likes_count':likes_count,
    }
    return JsonResponse(data, status=200)

При необходимости вы также можете возвращать ошибки с кодом состояния, отражающим проблему; return JsonResponse({"error": ""}, status=400)

Вернуться на верх