gpt4 book ai didi

python - django-rest-framework 中的 PDF

转载 作者:行者123 更新时间:2023-12-01 09:26:03 24 4
gpt4 key购买 nike

我正在尝试在 Django 中制作 pdf

 from xhtml2pdf import pisa
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from rest_framework.views import APIView
from .models import Brand

class ABCView(APIView):
def post(self, request,format=None):
report = Brand.objects.all()
template_path = 'profile_brand_report.html'

response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

context = {'report': report}
template = get_template(template_path)
html = template.render(Context(context))
print (html)

pisaStatus = pisa.CreatePDF(html, dest=response)

return response

但是我收到一个意外错误,我不知道我做错了什么,我收到此错误

argument of type 'Context' is not iterable

或者还有其他方法吗?提前感谢您的帮助

最佳答案

我们不需要使用基于类的 View 。为了简单起见,我们可以使用基于函数的 View 。如下更改您的代码。

from django.template.loader import render_to_string

def generate_pdf(request):
report = Brand.objects.all()
template_path = 'profile_brand_report.html'

response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

html = render_to_string(template_path, {'report': report})
print (html)

pisaStatus = pisa.CreatePDF(html, dest=response)

return response

我们还可以使用 wkhtmltopdf 在 django 中生成 PDF。
阅读:https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/

关于python - django-rest-framework 中的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50384613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com