On localhost it works perfectly fine but on pythonanywhere it doesn't work anymore. When I press on a button which should download a word document I get this error message: SystemError: returned a result with an error set. views.py:
def downloadWord(request, pk):
order = Order.objects.get(pk=pk)
order_items = order.order_items.all()
date = f'{order.date}'
d =date[8:]
y = date[:4]
m = date[5:7]
date = f'{d}.{m}.{y}'
context={
'order_items': order_items,
'order': order,
'date': date
}
byte_io = BytesIO()
tpl = DocxTemplate(os.path.join(BASE_DIR, 'media/word_documents/order.docx'))
tpl.render(context)
tpl.save(byte_io)
byte_io.seek(0)
data = dict()
return FileResponse(byte_io, as_attachment=True, filename=f'order_{order.title}.docx')
I also tried to use FileWrapper from werkzeug but then it says "AttributeError: 'FileWrapper' object has no attribute 'write'":
from werkzeug.wsgi import FileWrapper
def downloadWord(request, pk):
order = Order.objects.get(pk=pk)
order_items = order.order_items.all()
date = f'{order.date}'
d =date[8:]
y = date[:4]
m = date[5:7]
date = f'{d}.{m}.{y}'
context={
'order_items': order_items,
'order': order,
'date': date
}
byte_io = BytesIO()
byte_io = FileWrapper(byte_io)
tpl = DocxTemplate(os.path.join(BASE_DIR, 'media/word_documents/order.docx'))
tpl.render(context)
tpl.save(byte_io)
byte_io.seek(0)
return FileResponse(byte_io, as_attachment=True, filename=f'order_{order.title}.docx')
I think you might be creating those various streams in the wrong order -- try this:
tpl = DocxTemplate(os.path.join(BASE_DIR, 'media/word_documents/order.docx'))
tpl.render(context)
byte_io = BytesIO()
tpl.save(byte_io)
byte_io.seek(0)
return FileResponse(FileWrapper(byte_io), as_attachment=True, filename=f'order_{order.title}.docx')