猿问

将 Ajax 添加到评论部分不起作用

我正在尝试将 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.


aluckdog
浏览 107回答 1
1回答

翻翻过去那场雪

该函数get_context_data仅用于为上下文构建数据,不处理 ajax 请求。您需要拆分您的函数以提供对 GET 数据的处理结构示例class PostDetailView(DetailView):&nbsp; &nbsp; model = Post&nbsp; &nbsp; template_name = "blog/post_detail.html"&nbsp; # <app>/<model>_<viewtype>.html&nbsp; &nbsp; def get_context_data(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; [...]&nbsp; &nbsp; &nbsp; &nbsp; return context&nbsp; &nbsp; def get(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; if self.request.is_ajax():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context = self.get_context_data(self, *args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; html = render_to_string('blog/comments.html', context, request=self.request)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return JsonResponse({'form': html})&nbsp; &nbsp; &nbsp; &nbsp; [...]&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; def post(self, request, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; [...]
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答