简体   繁体   中英

Django: SystemError: <built-in function uwsgi_sendfile> returned a result with an error set

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM