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.
    • Hooking into the CSV-generation API is easy: Just pass response as thefirst argument to . The csv.writer function expects afile-like object, and objects fit thebill.
    • For each row in your CSV file, call writer.writerow, passing it aniterable object such as a list or tuple.

    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 Django template systemto generate CSV. This is lower-level than using the convenient Python module, 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 for 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 template is quite basic. It just iterates over the given data and displaysa line of CSV for each row. It uses the template filter toensure there aren't any problems with quotes.