python - 名称“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
我正在关注本教程:链接。
我该如何解决?
解决方案
似乎您已经跳过了教程中代码的导入部分,这应该就在您的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 了解更多信息。
推荐阅读
- php - 如何将图标列表小部件(Elementor)居中,图标在左侧对齐?
- java - ApplicationRunner VS CommandLineRunner
- html - 无法在导航栏中调整图像大小
- api - 如何解决过滤后的 API 结果导致 Vue 应用返回未定义?
- python - 使用python脚本准备命令行选项
- cs50 - 将用户输入添加到未知大小的数组
- javascript - 如何处理路径遍历?
- swiftui - 如何让preferenceKey 接受SwiftUI 中的视图?
- vba - VBA Word 动态插入文本 - ContentControl 的问题 - 替代方案?
- python - Toast Notifier 不工作,我做错了吗?