Django - __init__() 得到了一个意外的关键字参数 'headers'

Django - __init__() got an unexpected keyword argument 'headers'

我试图在单击按钮时下载 CSV,但是,我收到错误消息:

__init__() got an unexpected keyword argument 'headers

这是我的观点:

def download_file(request):
    response = HttpResponse(
        content_type='text/csv',
        headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'},
    )
    return response

这是引用:

Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "/Users/matthewkaye/Eflux/Argus/app/views.py" in download_file
  74.     response = HttpResponse(

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/http/response.py" in __init__
  289.         super().__init__(*args, **kwargs)

Exception Type: TypeError at /Download
Exception Value: __init__() got an unexpected keyword argument 'headers'

我假设您使用的是较旧的 Django 版本。在版本 2 中,无法在构造函数中设置 headers。尝试

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

另见 https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.HttpResponse.init