我正在使用 Django 1.11
,并且我正在尝试改进现有代码,以便将数据导出到 Excel 文件。有2种情况:
文件包含的行数少于 70.000。这样,用户就可以直接下载生成的输出文件。
文件包含超过 70.000 行。在本例中,文件写入媒体文件夹中。
我在第二部分遇到问题。
该文件在 Media 文件夹中写得很好,但我找不到提供 HttpResponse 对象的方法。
在我的 HTML 模板中,我有这个链接:
<a title="Export to Excel" class="button btn btn-default" href="{% url 'app:export-xls' model=model %}">
<span class="glyphicon glyphicon-export"></span>
</a>
在我看来,我有这个文件:
class ExportAPP(View):
def export_xls(self, model=""):
app_label = 'app'
# create a workbook in memory
output = io.BytesIO()
book = Workbook(output, {'constant_memory': True})
sheet = book.add_worksheet('Page 1')
# Sheet header, first row
row_num = 0
#Part which fill the file, adjust columns etc ..
...
book.close()
if len(rows) < 70000:
# construct response
output.seek(0)
name = 'Obsolete' if obsolete else ''
name += str(model._meta.verbose_name_plural)
response = HttpResponse(output.read(),
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = 'attachment; filename="' + name + '.xlsx"'
return response
#The interesting part
else:
print('Export contains more than 70.000 entries')
output.seek(0)
name = 'Obsolete' if obsolete else ''
name += str(model._meta.verbose_name_plural)
name = name + "_" + str(datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx'
file = default_storage.save(name, output)
我遇到这个问题:
View app.views.export.export_xls 未返回 HttpResponse 对象。它返回 None 相反。
我想返回相同的模板页面,但我找不到方法。
最佳答案
您的代码正在到达 else
语句。您没有在 else 语句中返回任何响应。应该是这样的
else:
print('Export contains more than 70.000 entries')
output.seek(0)
name = 'Obsolete' if obsolete else ''
name += str(model._meta.verbose_name_plural)
name = name + "_" + str(datetime.now().strftime("%Y_%m_%d_%H_%M_%s")) + '.xlsx'
file = default_storage.save(name, output)
return HttpResponseRedirect('/')
关于python - View 未返回 HttpResponse 对象。它返回 None 相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646879/