Django-链接以在模板中下载CSV

时间:2018-11-16 14:30:27

标签: python django django-models

试图弄清楚如何正确创建模板上csv文件的下载链接。

Views.py

#this is the view that shows the html page (all queries work)
def admin_view(request, mysite):
    context = dict()
    context["mysite"] = mysite.upper()
    group = whid.lower() + "-group"
    user = request.user.get_username()
    authorized = is_authorized(user, group)
    end_time = timezone.now()
    start_time = end_time.replace(day=1, hour=00, minute=00, second=00)
    error_message = ("You are not authorized to be in this page.")
    context['data'] = CheckIn.objects.filter(Date__range=(start_time, end_time))
    today = datetime.datetime.now()
    context['today'] = today
    context['first_day'] = today.replace(day=1, hour=00, minute=1)

    #Calling the csv function here
    context['response'] = export_search_csv(start_time, end_time) 

    if (authorized):
        return render(request, 'mykiosk/admin.html', context)
    else:
        return HttpResponse(error)


#function to grab and create csv
def export_search_csv(start_time, end_time):
    data = CheckIn.objects.filter(Date__range=(start_time, end_time))
    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

模板

<a href="{{ response}}">export to csv</a>

当我尝试访问链接时,我得到的只是一个<HttpResponse status_code=200, "text/csv">。我缺少了一些东西,只是不确定。根据公司内部规定,我也无法使用djqscsv库。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为您做错了方法。而不是通过上下文发送它,您应该将export_search_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'),