【问题标题】:name 'HTML' is not defined名称“HTML”未定义
【发布时间】:2021-02-04 17:59:13
【问题描述】:

我正在使用Django 项目并尝试使用WeasyPrint 呈现pdf。

我的views.py:

def WeasyPDF(request):
    paragraphs = ['first paragraph', 'second paragraph', 'third paragraph']
    html_string = render_to_string('app/pdf_report.html', {'paragraphs': paragraphs})

    html = HTML(string=html_string)
    html.write_pdf(
    target='/tmp/mypdf.pdf',
    stylesheets=[
        # Change this to suit your css path
        settings.BASE_DIR + 'css/bootstrap.min.css',
        settings.BASE_DIR + 'css/main.css',
    ],
    );

    fs = FileSystemStorage('/tmp')
    with fs.open('mypdf.pdf') as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
        return response
    return response

但它说以下错误:

name 'HTML' is not defined

我正在关注本教程:link

我该如何解决?

【问题讨论】:

  • 你导入过这样的名字吗?
  • 不,我没有导入那种东西。
  • 那就难怪没有定义了...
  • from weasyprint import HTML 来自WeasyPrint docs。看起来他们也有一个 Django 库:django-weasyprint

标签: python django


【解决方案1】:

您似乎跳过了教程中代码的导入部分,该部分应该就在您的 WeasyPDF 函数之上:

from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
from django.template.loader import render_to_string

from weasyprint import HTML

def WeasyPDF(request):

此外,我建议不要使用PascalCase 命名函数的风格——在python 中这很不方便,并且可能会误导您定义类而不是函数的人。 Read PEP8 for more information.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2018-01-24
    • 2018-02-21
    • 2020-07-31
    相关资源
    最近更新 更多