如何从Django Template创建和下载CSV

时间:2017-08-13 01:20:15

标签: django django-forms django-templates

我对Django很新,并且在提供文件方面做得不多,而且只使用Django模板从表单中提取和推送。

我的目标是:

使用用户表单中收集的信息,查询我的数据库并创建一个将下载给用户的CSV。

这是否可以使用基于模板的页面?

2 个答案:

答案 0 :(得分:1)

使用默认django的csv.writer

# In this example csv_request is the request model to save how many CSV requests came via your form
# DataForCSVModel is the Model you want to download as CSV

import csv
from django.http import HttpResponse

def some_view(request):
    # your business logic or whatever goes here
    if form.is_valid():
        csv_request = form.save(commit=False)
        csv_request.requested_by = request.user
        csv_request.requested_date= timezone.now()
        csv_request.save()

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="csv_filename.csv"'

    writer = csv.writer(response)
    [writer.writerow() for a in DataForCSVModel.objects.filter(<use csv_request object's data to filter>).values_list('id', 'name', 'place')]
    # Or if you want to write something else write like this
    # writer.writerow(['hello', 'world', 'Foo', 'Bar', 'Baz'])

    return response

或者

如果您不想承担风险,请使用django-queryset-csv

安装https://github.com/azavea/django-queryset-csv

from djqscsv import render_to_csv_response

def csv_view(request):
  qs = Foo.objects.filter(bar=True).values('id', 'bar')
  return render_to_csv_response(qs)

答案 1 :(得分:-1)

对于生成csv,我更喜欢熊猫,首先制作一个数据框,然后将其轻松转换为CSV

predicted_classes = []
true_classes = []
for i in range(len(train_flow)):  # you can just use `len(train_flow)` instead of `math.ceil(train_images.shape[0]/BATCH_SIZE))`
    x, y = train_flow[i]  # you can use `train_flow[i]` like this
    z = model.predict(x)
    for j in range(x.shape[0]):
        predicted_classes.append(z[j])
        true_classes.append(y[j])