我正在试图弄清楚如何在Django中下载文件。我在stackoverflow上经历了几个答案并尝试了这个:
views.py
def download():
file = open("DemoCSV.csv", "r")
response = HttpResponse(file,content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="DemoCSV.csv"'
return response
文件DemoCSV.csv与我的应用程序位于同一文件夹中。
当我从浏览器点击网址时,我无法下载该文件。显示以下错误消息:
TypeError at /resources/download_files
download() takes 0 positional arguments but 1 was given
我错过了什么?
答案 0 :(得分:1)
看起来download
是一个视图,因此它需要一个参数,一个HttpRequest对象。所以改变如下
def download(request):
file = open("DemoCSV.csv", "r")
response = HttpResponse(file,content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="DemoCSV.csv"'
return response