首页IT科技output什么接口(Outputting CSV with Django¶)

output什么接口(Outputting CSV with Django¶)

时间2025-06-15 00:23:21分类IT科技浏览4127
导读:Outputting CSV with Django¶...

Outputting CSV with Django¶

This document explains how to output CSV (Comma Separated Values) dynamically

using Django views. To do this, you can either use the Python CSV library or the

Django template system.

Using the template system¶

Alternatively, you can use the Django template system

to generate CSV. This is lower-level than using the convenient Python csv module, but the solution is presented here for completeness.

The idea here is to pass a list of items to your template, and have the

template output the commas in a for loop.

Heres an example, which generates the same CSV file as above:

from django.http import HttpResponse from django.template import loader, Context def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(mimetype=text/csv) response[Content-Disposition] = attachment; filename=somefilename.csv # The data is hard-coded here, but you could load it from a database or # some other source. csv_data = ( (First row, Foo, Bar, Baz), (Second row, A, B, C, "Testing", "Heres a quote"), ) t = loader.get_template(my_template_name.txt) c = Context({ data: csv_data, }) response.write(t.render(c)) return response

The only difference between this example and the previous example is that this

one uses template loading instead of the CSV module. The rest of the code --

such as the mimetype=text/csv -- is the same.

Then, create the template my_template_name.txt, with this template code:

{% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}" {% endfor %}

This template is quite basic. It just iterates over the given data and displays

a line of CSV for each row. It uses the addslashes

template filter to

ensure there arent any problems with quotes.

Other text-based formats¶

Notice that there isnt very much specific to CSV here -- just the specific

output format. You can use either of these techniques to output any text-based

format you can dream of. You can also use a similar technique to generate

arbitrary binary data; see Outputting PDFs with Django for an example.
声明:本站所有文章             ,如无特殊说明或标注                   ,均为本站原创发布             。任何个人或组织      ,在未征得本站同意时             ,禁止复制             、盗用                   、采集      、发布本站内容到任何网站       、书籍等各类媒体平台                   。如若本站内容侵犯了原著者的合法权益                   ,可联系我们进行处理      。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
网站实现过程中遇到的问题及解决办法(什么是网站解决方案,如何选择适合的网站解决方案) 用js做一个倒计时(时分秒)(如何利用js来制作时间倒计时效果)