Outputting CSV with Django
Python comes with a CSV library, . The key to using it with Django is that the module’s CSV-creation capability acts on file-like objects, and Django’s HttpResponse
objects are file-like objects.
Here’s an example:
The code and comments should be self-explanatory, but a few things deserve a mention:
- The response gets a special MIME type, text/csv. This tells browsers that the document is a CSV file, rather than an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will result in ugly, scary gobbledygook in the browser window.
- You can hook into the CSV-generation API by passing
response
as the first argument to . Thecsv.writer
function expects a file-like object, and objects fit the bill. - For each row in your CSV file, call
writer.writerow
, passing it an iterable.
In this example, we make full use of Python generators to efficiently handle the assembly and transmission of a large CSV file:
Alternatively, you can use the 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 loop.
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 content_type='text/csv'
– is the same.
Then, create the template my_template_name.txt
, with this template code:
This short template iterates over the given data and displays a line of CSV for each row. It uses the template filter to ensure there aren’t any problems with quotes.