首页 > 解决方案 > 名称“HTML”未定义

问题描述

我正在处理该Django项目并尝试使用WeasyPrint.

我的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

我正在关注本教程:链接

我该如何解决?

标签: pythondjango

解决方案


似乎您已经跳过了教程中代码的导入部分,这应该就在您的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 中,这很不方便,并且可能会误导您定义类而不是函数的人。阅读 PEP8 了解更多信息


推荐阅读