亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 Ajax 添加到評論部分不起作用

將 Ajax 添加到評論部分不起作用

aluckdog 2023-08-18 17:26:44
我正在嘗試將 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條經驗 獲得超14個贊

該函數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):

        [...]


查看完整回答
反對 回復 2023-08-18
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號