【问题标题】:Django: SystemError: <built-in function uwsgi_sendfile> returned a result with an error setDjango: SystemError: <built-in function uwsgi_sendfile> 返回了带有错误集的结果
【发布时间】:2025-12-29 13:35:07
【问题描述】:

在 localhost 上它工作得非常好,但在 pythonanywhere 上它不再工作了。当我按下应该下载 Word 文档的按钮时,我收到以下错误消息: SystemError:返回带有错误集的结果。 视图.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')

我也尝试使用 werkzeug 的 FileWrapper,但它显示“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')

【问题讨论】:

    标签: python django pythonanywhere python-docx


    【解决方案1】:

    我认为您可能以错误的顺序创建了这些不同的流——试试这个:

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

    【讨论】:

      最近更新 更多