视图未返回HttpResponse对象。它返回None instaed

时间:2019-02-12 09:35:39

标签: python django httpresponse

我正在使用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)

我遇到了这个问题:

The view app.views.export.export_xls didn't return an HttpResponse object. It returned None instead.

我想返回相同的模板页面,但是我没有找到一种方法。

2 个答案:

答案 0 :(得分:2)

您的代码正在到达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('/')

答案 1 :(得分:0)

您应该在此处返回一些内容,或者某个页面或代码200,或者重定向到某个页面(返回HttpResponseRedirect('/ thanks /')):

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)