Django / xhtml2pdf - объект не имеет атрибута "закодировать"
Мне трудно создавать PDF в Django. Согласно моему предыдущему вопросу, я сталкиваюсь с той же ошибкой.
Когда я запускаю следующий код, я получаю 'list' object has no attribute 'encode'
PDF-файл сохраняется в папке мультимедиа, но это обычный текстовый файл. Я думаю, что объект, который упоминается, является sections
QuerySet.
@login_required
def generate_pdf(request, slug):
# Prepare context
document = get_object_or_404(Document, slug=slug)
sections = \
get_list_or_404(Section.objects.filter
(associated_document__startswith=document.slug))
data = {'document': document, 'sections': sections}
# Render html content through html template with context
template = get_template('lld/lld_pdf.html')
html = template.render(Context(data))
file = open('/home/project/media/test.pdf', "w+b")
print type(document)
print type(sections)
print type(data)
print type(template)
print type(html)
print type(file)
pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file)
# Return PDF document through a Django HTTP response
file.seek(0)
pdf = file.read()
file.close() # Don't forget to close the file handle
return HttpResponse(pdf, mimetype='application/pdf')
Cli выход:
<class 'lld.models.Document'>
<type 'list'>
<type 'dict'>
<class 'django.template.backends.django.Template'>
<class 'django.utils.safestring.SafeText'>
<type 'file'>
и ошибка:
Environment:
Request Method: GET
Request URL: http://localhost:8001/lld/tesco-greenfield-datacenter-deployment/pdf/
Django Version: 1.8.2
Python Version: 2.7.6
Installed Applications:
('django_admin_bootstrapped',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'lld',
'registration')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "/home/vagrant/shared/RepeatableDesign/lld/views.py" in generate_pdf
162. pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/document.py" in pisaDocument
89. encoding, context=context, xml_output=xml_output)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/document.py" in pisaStory
57. pisaParser(src, context, default_css, xhtml, encoding, xml_output)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/parser.py" in pisaParser
685. context.parseCSS()
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/context.py" in parseCSS
498. self.css = self.cssParser.parse(self.cssText)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in parse
434. src, stylesheet = self._parseStylesheet(src)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in _parseStylesheet
522. src, stylesheetImports = self._parseAtImports(src)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in _parseAtImports
606. stylesheet = self.cssBuilder.atImport(import_, mediums, self)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/css.py" in atImport
874. return cssParser.parseExternal(import_)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/context.py" in parseExternal
380. result = self.parse(cssFile.getData())
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in parse
434. src, stylesheet = self._parseStylesheet(src)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in _parseStylesheet
533. src, atResults = self._parseAtKeyword(src)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in _parseAtKeyword
655. src, result = self._parseAtFontFace(src)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/w3c/cssParser.py" in _parseAtFontFace
785. result = [self.cssBuilder.atFontFace(properties)]
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/context.py" in atFontFace
173. src = self.c.getFile(data["src"], relative=self.c.cssParser.rootPath)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/context.py" in getFile
823. return getFile(name, relative or self.pathDirectory)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/util.py" in getFile
635. file = pisaFileObject(*a, **kw)
File "/usr/local/lib/python2.7/dist-packages/xhtml2pdf/util.py" in __init__
516. uri = uri.encode('utf-8')
Exception Type: AttributeError at /lld/tesco-greenfield-datacenter-deployment/pdf/
Exception Value: 'list' object has no attribute 'encode'
1 ответ
Решение
Я даже не могу поверить, что провел несколько дней, плача и рвя волосы, потому что я использовал шрифт Google. Да, как только я удалил <link href="http://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
из моего шаблона ошибка vamoosed!