简体   繁体   English

Django - 如何下载文件

[英]Django - how to download a file

I am trying to create a download button in my template for a csv file generated by my website (I am new to Django).我正在尝试在我的模板中为我的网站生成的 csv 文件创建一个下载按钮(我是 Django 新手)。 I have created the view function and updated urls.py but I get 'DoesNotExist: Page matching query does not exist' when I input the url (' http://127.0.0.1:8000/download_table '). I have created the view function and updated urls.py but I get 'DoesNotExist: Page matching query does not exist' when I input the url (' http://127.0.0.1:8000/download_table '). I'd also like to know how to create a link/button to the download in my html template.我还想知道如何在我的 html 模板中创建下载链接/按钮。

views.py:视图.py:

def download_csv(request):
table_selected = request.POST.get('Table_select')
index_of_table_selected = int(re.search(r'\d+$', table_selected).group())
result_json_selected = request.session.get('result', 'missing')[index_of_table_selected]
dataframe_selected = pd.read_json(result_json_selected)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'Table.csv'
dataframe_selected.to_csv(path_or_buf=response, sep=';', float_format='%.2f', index=False, decimal=",")

return response

urls.py:网址.py:

urlpatterns = [
path('', views.index, {'pagename': ''}, name='home'),
path('<str:pagename>', views.index, name='index'),
path('download_table/', views.download_csv, name='download_csv'),]

Also, what do I put in my template?另外,我在模板中放了什么? Something like this?像这样的东西?

<a href="download_table/" download> Download File</a>

That link returns the error该链接返回错误

TypeError: download_csv() got an unexpected keyword argument 'filepath' TypeError:download_csv() 得到了一个意外的关键字参数“文件路径”

You're getting 404 because This is the 'app' level urls.py , You need to link it to the 'project' level urls.py你得到 404 因为这是 'app' 级别urls.py ,你需要将它链接到 'project' 级别urls.py

The second error is because download_csv(request) should be download_csv(request, filepath) or better yet, use download_csv(request, **kwargs) It says it got an argument (eg localhost:8000/argument/ ) and you have no variable to contain it.第二个错误是因为download_csv(request)应该是download_csv(request, filepath)或者更好,使用download_csv(request, **kwargs)它说它有一个参数(例如localhost:8000/argument/ )并且你没有变量包含它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM