[英]Using ReportLab To Create A PDF Then Save It To A User Model
幾天來,我一直試圖讓這個工作,雖然我認為我已經接近了,但我仍然沒有讓它工作。
我有一個 function,它使用 ReportLab 生成一個 SimpleDocTemplate pdf,我想將它返回到調用視圖,以便我可以將其保存到用戶配置文件 Z20F35E630DAF44DBFA4C3F68F593。
到目前為止,這是我的代碼:
model.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pdf = models.FileField(upload_to='pdfs/user_pdfs')
錯誤信息:
'HttpResponse' object has no attribute 'read'
看法
def final_question(request):
if request.method == 'POST':
# this is the final form they complete
form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion)
if form.is_valid():
form.save()
# generate pdf containing all answers to enrolment questions
users_pdf = utils.generate_user_pdf(request)
# here i get the users model
# hard coded user_id for testing
users_profile = Profile.objects.get(user_id=1)
# then i get the field I want to save to
pdf = users_profile.profile_pdf
# then i save the generated pdf to the field
pdf.save('user_1_pdf', users_pdf)
我的 pdf 一代 function
def generate_user_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename = "test.pdf"'
doc = SimpleDocTemplate(response)
elements = []
data= [
['---TEST DATA---'],
['test data'],
]
[.. cont ..]
doc.build(elements)
return response
謝謝你。
- 編輯 -
錯誤:
argument should be a bytes-like object or ASCII string, not 'FileResponse'
實用程序:
def generate_pdf(request):
buffer = io.BytesIO()
doc = SimpleDocTemplate('test')
story = []
doc.build(story)
response = FileResponse(buffer.getvalue())
return response
視圖.py
# generate pdf containing all answers
user_pdf = utils.generate_pdf(request)
# get users enrolment_pdf field
# temp hard-coded
user_profile = Profile.objects.get(user_id=1)
field = user_profile.user_pdf
# save the generated pdf to the user in the database
file_data = ContentFile(base64.b64decode(user_pdf))
field.save('test', file_data)
謝謝
首先, 有一個答案。 除了這個答案,您還需要閱讀這個,只需使用buffer.getvalue()
字節數組並使用ContentFile
class 將其保存到 model 字段。
要簡化使用 Response object 的工作,請使用FileResponse 。
- 編輯 -
您需要將 pdf 寫入緩沖區:
doc = SimpleDocTemplate(buffer)
doc.build(story)
buffer.seek(0)
pdf: bytes = buffer.getvalue()
return FileResponse(pdf, filename='doc.pdf')
而且,我在文檔中找到了這些說明。
要將 pdf 保存到Profile
中:
file_data = ContentFile(pdf)
profile = Profile.objects.get(...)
profile.pdf_field.save('filename.pdf', file_data, save=False)
profile.save()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.