View 没有 return HttpResponse 对象。它 returned None instaed

View didn't return an HttpResponse object. It returned None instaed

我正在使用 Django 1.11,我正在尝试改进现有代码,以便将数据导出到 Excel 文件。有2个案例:

我遇到了第二部分的问题。

Media 文件夹中的文件写得很好,但我找不到提供 HttpResponse 对象的方法。

在我的 HTML 模板中,我有这个 link :

<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.

我想 return 相同的模板页面,但找不到方法。

你应该 return 在这里,某个页面或代码 200,或者,也许重定向到某个页面 (return 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)

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