Python Django-在模板中下载CSV的链接
试图找出如何在我的模板上正确创建指向csv文件的下载链接 Views.py 模板Python Django-在模板中下载CSV的链接,python,django,django-models,Python,Django,Django Models,试图找出如何在我的模板上正确创建指向csv文件的下载链接 Views.py 模板 当我尝试访问链接时,我得到的只是一个。我错过了一些东西,我只是不知道是什么。由于公司内部规定,我也不能使用djqscsv库 非常感谢您的帮助。我认为您做得不对。您应该将export\u search\u csv方法转换为视图并从模板中使用,而不是通过上下文发送。例如: def export_search_csv(request, start_date, end_date): data = CheckIn
当我尝试访问链接时,我得到的只是一个
。我错过了一些东西,我只是不知道是什么。由于公司内部规定,我也不能使用djqscsv
库
非常感谢您的帮助。我认为您做得不对。您应该将
export\u search\u csv
方法转换为视图并从模板中使用,而不是通过上下文发送。例如:
def export_search_csv(request, start_date, end_date):
data = CheckIn.objects.filter(Date__range=(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S"), datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")))
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="export.csv"'
writer = csv.writer(response)
writer.writerow(['id', 'EmpID', 'BarID', 'Username', 'Type', 'Liability', 'Date'])
for item in data:
writer.writerow([item.id, item.EmpID, item.BarID, item.Username, item.Type, item.Liability, item.Date])
return response
def admin_view(request, mysite):
...
context['start_date'] = startdate.strftime("%Y-%m-%d %H:%M:%S")
context['end_date'] = enddate.strftime("%Y-%m-%d %H:%M:%S")
...
在模板中:
<a href="{% url 'export_search_csv' start_date end_date %}">export to csv</a>
为新视图添加新的url:
path('your_path/<str:start_date>/<str:end_date>/', export_search_csv, name='export_search_csv'),
path('your_path//',export_search_csv,name='export_search_csv'),
<a href="{% url 'export_search_csv' start_date end_date %}">export to csv</a>
path('your_path/<str:start_date>/<str:end_date>/', export_search_csv, name='export_search_csv'),