使用Django生成CSV文件(动态内容) [英] Generating CSV file with Django (dynamic content)

查看:213
本文介绍了使用Django生成CSV文件(动态内容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在view.py中,我有两个功能,一个处理来自表单的输入并输出过滤的列表,另一个应该将列表导出为CSV.

Inside my view.py, I have two functions, one that processes input from a form and outputs a filtered list, and another that is supposed to export this list to CSV.

这是我第一个函数的返回:

Here is the return of my first function:

return render_to_response('templateX.html',
{
 'queryset': queryset,
 'filter_form': filter_form,
 'validated': validated,
},
 context_instance = RequestContext(request)
 )

这是导出功能:

def export_to_csv(request):
    # get the response object, this can be used as a stream.
    response = HttpResponse(mimetype='text/csv')
    # force download.
    response['Content-Disposition'] = 'attachment;filename=export.csv'
    # the csv writer
    writer = csv.writer(response)
    qs = request.session['queryset']
    for cdr in qs:
        writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
    return response   

我不确定如何从第一个函数中获取 queryset ,该函数包含要在CSV中使用的项的列表,并在我的export_to_csv函数中使用它. 或者最好的方法是将这两个功能结合起来,并让用户单击复选框,确定他/她是否要下载CSV文件. 任何帮助将不胜感激.

I'm not sure how to get the queryset from my first function, which contains a list of the items I want in my CSV and use it in my export_to_csv function. Or would the best way be combining these two functions and have the user click on a checkbox whether he/she wants to download a CSV file. Any help would be appreciated.

推荐答案

我建议将它们组合成一个需要额外参数的视图函数:

I'd recommend combining these into one view function which takes an extra parameter:

def my_view(request, exportCSV):
    # ... Figure out `queryset` here ...

    if exportCSV:
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment;filename=export.csv'
        writer = csv.writer(response)
        for cdr in queryset:
            writer.writerow([cdr['calldate'], cdr['src'], cdr['dst'], ])
        return response
    else:
        return render_to_response('templateX.html', {'queryset': queryset,
            'filter_form': filter_form, 'validated': validated},
            context_instance = RequestContext(request))

然后,在您的urls.py中,将这样的内容放入您的urlpatterns:

Then, in your urls.py, put something like this in your urlpatterns:

url(r'^form', 'my_view', {"exportCSV": False}, name="form"),
url(r'^csv', 'my_view', {"exportCSV": True}, name="export"),

这篇关于使用Django生成CSV文件(动态内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆