Django – __init__() got an unexpected keyword argument ‘headers’

I am trying to download a CSV when a button is clicked, however, I am getting the error:

__init__() got an unexpected keyword argument 'headers

this is my view:

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

this is the trackback:

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'

Answer

I assume that you are using an older Django version. In version 2, it is not possible to set the headers in the constructor. Try

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

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