我正在尝试将 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.
翻翻过去那场雪
相关分类