gpt4 book ai didi

django - “WSGIRequest”对象在 django 4 中没有属性 'is_ajax'

转载 作者:行者123 更新时间:2023-12-03 08:06:59 25 4
gpt4 key购买 nike

我用 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':

而不是

如果 request.is_ajax:

关于django - “WSGIRequest”对象在 django 4 中没有属性 'is_ajax',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71988457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com