使用wkhtmltopdf在Django中生成pdf

4
我正在尝试使用这个库创建PDF,实现文档中最简单的示例。可以像这样使用URL并直接从模板渲染。
url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                                       filename='my_pdf.pdf'), name='pdf'),

这是模板文件的html代码。
<!DOCTYPE html>
<html>
 <head>
    <title>Hello Wold</title>
 </head>
    <body>
       <p>My First Pdf</p>
     </body>
</html>

但是当我尝试这个链接时,出现了错误:

在/pdf/处发生AttributeError: 'NoneType'对象没有'endswith'属性

我该如何解决这个问题呢?

这是Traceback:

Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 139. response = response.render() File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render 105. self.content = self.rendered_content File "/usr/local/lib/python2.7/dist-packages/wkhtmltopdf/views.py" in rendered_content 123. delete=(not debug) File "/usr/local/lib/python2.7/dist-packages/wkhtmltopdf/views.py" in render_to_temporary_file 78. content = make_absolute_paths(content) File "/usr/local/lib/python2.7/dist-packages/wkhtmltopdf/utils.py" in make_absolute_paths 151. if not x['root'].endswith('/'):

异常类型:在/pdf/处发生AttributeError: 'NoneType'对象没有'endswith'属性

环境:

请求方式:GET

Django Version: 1.6.2
Python Version: 2.7.3
Installed Applications:
    ('django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'south',
     'rest_framework',
     'cian',
     'django_extensions',
     'wkhtmltopdf')
Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware')

这是带有Django-wkhtmltopdf错误的截图。
3个回答

5

出现此错误是因为wkhtmltopdf使用settings.py中STATIC_ROOT的路径生成pdf文件。尝试给STATIC_ROOT赋值并进行测试。

STATIC_ROOT = 'path.to.your.static.directory'

1

看起来您的根路径存在问题。尝试在Django设置文件(settings.py)中设置STATIC_URL。


我有这样的静态路径:STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'frontend'), )我不明白我的问题出在哪里或为什么会出现异常AttributeError at /pdf/ 'NoneType' object has no attribute 'endswith' - mch505

0
错误在于我没有在settings.py中定义我的media_root和media_url,包装器期望你有static_root、media_root、static_url和media_url才能正常工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接