使用django_xhtml2pdf与django 1.11"错误:上下文必须是dict而不是Context。"

时间:2017-09-03 23:58:59

标签: python django xhtml2pdf

根据其中一条评论:我确实将我的代码更改为:

providers = Provider.objects.all()
context = { 'providers':providers}

我知道它没有什么区别,但我想我会尝试它,因为发生了奇怪的事情。我担心错误是在我的django版本上运行的模块本身。

我确实看到了其他答案,这让我很困惑,因为我只是使用了这里记载的内容:

https://spapas.github.io/2015/11/27/pdf-in-django/#django-integration

让django_xhtml2pdf的东西工作。我的观点是这样的:

def providers_plain_old_view(request):
    resp = HttpResponse(content_type='application/pdf')
    context = {
        'providers': Provider.objects.all()
    }

    result = generate_pdf('ipaswdb/provider/providers_plain_old_view.html', file_object=resp, context=context)
    return result

我现在知道的是django 1.11.14我不习惯,但不知道如何修复错误:

Traceback (most recent call last):
  File "D:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Programming\web\ipa_django\mysite\ipaswdb\views.py", line 312, in providers_plain_old_view
    result = generate_pdf('ipaswdb/provider/providers_plain_old_view.html', file_object=resp, context=context)
  File "D:\Python27\lib\site-packages\django_xhtml2pdf\utils.py", line 62, in generate_pdf
    generate_pdf_template_object(tmpl, file_object, context)
  File "D:\Python27\lib\site-packages\django_xhtml2pdf\utils.py", line 39, in generate_pdf_template_object
    html = template_object.render(Context(context))
  File "D:\Python27\lib\site-packages\django\template\backends\django.py", line 64, in render
    context = make_context(context, request, autoescape=self.backend.engine.autoescape)
  File "D:\Python27\lib\site-packages\django\template\context.py", line 287, in make_context
    raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than Context.
"GET /ipaswdb/provider_roster/ HTTP/1.1" 500 86485

我的意思是它要我在最新的django版本中以不同的方式调用generate_pdf函数?

1 个答案:

答案 0 :(得分:2)

主要问题在于

File "D:\Python27\lib\site-packages\django_xhtml2pdf\utils.py", line 39, in generate_pdf_template_object
html = template_object.render(Context(context))

在错误输出中。这是一个问题,django-xhtml2pdf包不是1.11的最新版本。对渲染的调用已从

更改
html = template_object.render(Context(context))

html = template_object.render(context)

根据升级到1.11注释https://docs.djangoproject.com/en/1.11/ref/templates/upgrading/ django.template.loader section。

您可以等待他们修复它,提交错误报告或实现您在views.py中提供的功能