Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django-在模板中下载CSV的链接_Python_Django_Django Models - Fatal编程技术网

Python Django-在模板中下载CSV的链接

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

试图找出如何在我的模板上正确创建指向csv文件的下载链接

Views.py 模板

当我尝试访问链接时,我得到的只是一个
。我错过了一些东西,我只是不知道是什么。由于公司内部规定,我也不能使用
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'),