Home > Mobile >  'WSGIRequest' object has no attribute 'is_ajax' in django 4
'WSGIRequest' object has no attribute 'is_ajax' in django 4

Time:04-25

i had built a website with django 3 and i updated it to django 4 since this update i get this error I need help to solve this problem, thank you

'WSGIRequest' object has no attribute 'is_ajax'

this is my views

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})

thank you

CodePudding user response:

To solve this problem, add "XMLHttpRequest" to your headers like this.

# app.js

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

or like this:

fetch('YourURL', { method: "POST",headers: { "X-Requested-With": "XMLHttpRequest" }, body: form})

CodePudding user response:

request.is_ajax is deprecated since django 3.1 and has been removed since django 4. You can use

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

instead of

if request.is_ajax:

  • Related