【问题标题】:TypeError: context must be a dict rather than JsonResponseTypeError:上下文必须是字典而不是 JsonResponse
【发布时间】:2020-08-31 11:40:52
【问题描述】:

我正在尝试在基于类的 Listview 中使用 ajax 进行分页。

#views.py
class HomePage(ListView):
   model = Video
   template_name = 'index.html'


   def get_context_data(self, **kwargs):
      context = super(HomePage, self).get_context_data(**kwargs)
      videos = Video.objects.filter(category='sub')
      paginator = Paginator(videos, 5)
      page = self.request.GET.get('page2')
      try:
          videos = paginator.page(page)
      except PageNotAnInteger:
          videos = paginator.page(1)
      except EmptyPage:
          videos = paginator.page(paginator.num_pages)

   context['videos'] = videos

   if self.request.is_ajax():
       html = render_to_string('video/index2.html', context,   request=self.request)
       return JsonResponse({'form' : html })
        
   else:
       return context

我使用此视图时遇到的错误是:-

TypeError: context must be a dict rather than JsonResponse.

如果您有任何不同的方式来实现此 ajax 分页。请提及。提前谢谢。

【问题讨论】:

  • 你是不是这样尝试return JsonResponse(html) 而不是return JsonResponse({'form' : html }) ??
  • 我试过了,但又出现了一个错误。TypeError: 为了允许序列化非字典对象,请将安全参数设置为 False。
  • 请像print(html)这样打印html变量以检查是否有数据。
  • 控制台没有打印任何内容
  • Video 表没有数据??

标签: django django-views django-templates


【解决方案1】:

请使用return JsonResponse(html, safe=False) 而不是return JsonResponse({'form' : html })

【讨论】:

  • 不,仍然错误 TypeError: context must be a dict 而不是 JsonResponse。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 2019-02-01
  • 2017-10-02
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多