Outputting CSV with Django

    Python comes with a CSV library, . The key to using it with Django isthat 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 amention:

    • The response gets a special MIME type, text/csv. This tellsbrowsers that the document is a CSV file, rather than an HTML file. Ifyou 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 firstargument to . The csv.writer function expects a file-likeobject, and objects fit the bill.
    • For each row in your CSV file, call writer.writerow, passing it aniterable.

    In this example, we make full use of Python generators to efficiently handlethe 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 csvmodule, but the solution is presented here for completeness.

    The idea here is to pass a list of items to your template, and have thetemplate output the commas in a loop.

    The only difference between this example and the previous example is that thisone 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 foreach row. It uses the template filter to ensure therearen’t any problems with quotes.