Django 响应期望从视图返回一个“Response”、“HttpResponse”或“HttpStreamingResponse”,但收到一个“<class 'NoneType'>”

Django response Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

我的模型有属性字段作为文件和上传者,在我的例子中,当模型中没有数据时,我想在我的网站前端显示错误 no file found 而是它带我对于这个错误,我已经像这样实现了我的代码

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        if data:
            response = HttpResponse(
                data.file,
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

            )
            return response
    except FileNotFoundError:
        raise ValueError('No file found')

也许您可以 return 400 错误而不是 re-raising ValueError 例如

@api_view(('GET',))
def template_view(request):
    data = Mymodel.objects.first()
    try:
        response = HttpResponse(
            data.file,
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, '
                             'application/vnd.ms-excel',

        )
        return response
    except (FileNotFoundError, AttributeError):
        return HttpResponse("No File Found", status=400)

我还会捕获 AttributeError 而不是为数据添加 if 语句