Объект 'WSGIRequest' не имеет атрибута 'is_ajax' в django 4

я создал сайт на django 3 и обновил его до django 4 после этого обновления я получаю эту ошибку мне нужна помощь, чтобы решить эту проблему, спасибо

У объекта 'WSGIRequest' нет атрибута 'is_ajax'

Это мое мнение

views.py

def SingleBlog(request, Slug):
post = get_object_or_404(Blog, Slug=Slug, Status="p")
comments = BlogComment.objects.filter(Post=post, Reply=None, Status="p")
is_liked = False
if post.Like.filter(id=request.user.id).exists():
    is_liked = True

if request.method == 'POST':
    comment_form = CommentForm(request.POST or None)
    if comment_form.is_valid:
        content = request.POST.get('Text')
        reply_id = request.POST.get('comment_id')
        comment_qs = None
        if reply_id:
            comment_qs = BlogComment.objects.get(id=reply_id)
        comment = BlogComment.objects.create(Post=post, User=request.user, Text=content, Reply=comment_qs)
        comment.save()
        # return HttpResponseRedirect(post.get_absolute_url())
else:
    comment_form = CommentForm()

context = {
    'object': post,
    'comments': comments,
    'is_liked': is_liked,
    'comment_form': comment_form,
}
if request.is_ajax():
    html = render_to_string('partial/comments.html', context, request=request)
    return JsonResponse({'form': html})
return render(request, 'blog-single.html', context)

def post_like(request):
# post = get_object_or_404(Blog, id=request.POST.get('post_id'))
post = get_object_or_404(Blog, id=request.POST.get('id'))
is_liked = False
if post.Like.filter(id=request.user.id).exists():
    post.Like.remove(request.user)
    is_liked = False
else:
    post.Like.add(request.user)
    is_liked = True

context = {
    'object': post,
    'is_liked': is_liked,
}
if request.is_ajax():
    html = render_to_string('partial/like_section.html', context, request=request)
    return JsonResponse({'form': html})

спасибо

request.is_ajax устарел с django 3.1 и был удален с django 4. Вы можете использовать

if request.headers.get('x-requested-with') == 'XMLHttpRequest':

вместо

if request.is_ajax:

Чтобы решить эту проблему, добавьте "XMLHttpRequest" в заголовки следующим образом.

# app.js

headers: {
    "X-Requested-With": "XMLHttpRequest"
}

или вот так:

fetch('YourURL', { method: "POST",headers: { "X-Requested-With": "XMLHttpRequest" }, body: form})
Вернуться на верх