'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). 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.
views.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:
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'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
