我正在尝试将 Ajax 添加到我的评论部分,以避免每次添加评论时刷新页面。因此,我将评论部分从 new comments.html 加载到 post-details.html,并按照 Ajax 实现帖子,但我的问题是它没有产生任何效果,页面需要刷新才能显示新评论我在views.py 中对Generic DetailView 类进行了子类化,并尝试找出一种基于URL 中收到的参数以JSON 格式返回数据的方法。这是我尝试做的事情:class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment_qs = None comment = Comment.objects.create( post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect("blog/post_detail.html") else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked if self.request.is_ajax(): html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': html}) else: return context但这给了我 TypeError ,它应该是:TypeError: context must be a dict rather than JsonResponse.
1 回答
翻翻过去那场雪
TA贡献2065条经验 获得超13个赞
该函数get_context_data仅用于为上下文构建数据,不处理 ajax 请求。您需要拆分您的函数以提供对 GET 数据的处理
结构示例
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html
def get_context_data(self, *args, **kwargs):
[...]
return context
def get(self, request, *args, **kwargs):
if self.request.is_ajax():
context = self.get_context_data(self, *args, **kwargs)
html = render_to_string('blog/comments.html', context, request=self.request)
return JsonResponse({'form': html})
[...]
def post(self, request, *args, **kwargs):
[...]
添加回答
举报
0/150
提交
取消