outputting-csv.txt 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. ==========================
  2. Outputting CSV with Django
  3. ==========================
  4. This document explains how to output CSV (Comma Separated Values) dynamically
  5. using Django views. To do this, you can either use the `Python CSV library`_ or
  6. the Django template system.
  7. .. _Python CSV library: http://docs.python.org/library/csv.html
  8. Using the Python CSV library
  9. ============================
  10. Python comes with a CSV library, ``csv``. The key to using it with Django is
  11. that the ``csv`` module's CSV-creation capability acts on file-like objects, and
  12. Django's :class:`~django.http.HttpResponse` objects are file-like objects.
  13. Here's an example::
  14. import csv
  15. from django.http import HttpResponse
  16. def some_view(request):
  17. # Create the HttpResponse object with the appropriate CSV header.
  18. response = HttpResponse(mimetype='text/csv')
  19. response['Content-Disposition'] = 'attachment; filename=somefilename.csv'
  20. writer = csv.writer(response)
  21. writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
  22. writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])
  23. return response
  24. The code and comments should be self-explanatory, but a few things deserve a
  25. mention:
  26. * The response gets a special MIME type, ``text/csv``. This tells
  27. browsers that the document is a CSV file, rather than an HTML file. If
  28. you leave this off, browsers will probably interpret the output as HTML,
  29. which will result in ugly, scary gobbledygook in the browser window.
  30. * The response gets an additional ``Content-Disposition`` header, which
  31. contains the name of the CSV file. This filename is arbitrary; call it
  32. whatever you want. It'll be used by browsers in the "Save as..."
  33. dialogue, etc.
  34. * Hooking into the CSV-generation API is easy: Just pass ``response`` as the
  35. first argument to ``csv.writer``. The ``csv.writer`` function expects a
  36. file-like object, and :class:`~django.http.HttpResponse` objects fit the
  37. bill.
  38. * For each row in your CSV file, call ``writer.writerow``, passing it an
  39. iterable object such as a list or tuple.
  40. * The CSV module takes care of quoting for you, so you don't have to worry
  41. about escaping strings with quotes or commas in them. Just pass
  42. ``writerow()`` your raw strings, and it'll do the right thing.
  43. Handling Unicode
  44. ~~~~~~~~~~~~~~~~
  45. Python's ``csv`` module does not support Unicode input. Since Django uses
  46. Unicode internally this means strings read from sources such as
  47. :class:`~django.http.HttpRequest` are potentially problematic. There are a few
  48. options for handling this:
  49. * Manually encode all Unicode objects to a compatible encoding.
  50. * Use the ``UnicodeWriter`` class provided in the `csv module's examples
  51. section`_.
  52. * Use the `python-unicodecsv module`_, which aims to be a drop-in
  53. replacement for ``csv`` that gracefully handles Unicode.
  54. For more information, see the Python `CSV File Reading and Writing`_
  55. documentation.
  56. .. _`csv module's examples section`: http://docs.python.org/library/csv.html#examples
  57. .. _`python-unicodecsv module`: https://github.com/jdunck/python-unicodecsv
  58. .. _`CSV File Reading and Writing`: http://docs.python.org/library/csv.html
  59. Using the template system
  60. =========================
  61. Alternatively, you can use the :doc:`Django template system </topics/templates>`
  62. to generate CSV. This is lower-level than using the convenient Python ``csv``
  63. module, but the solution is presented here for completeness.
  64. The idea here is to pass a list of items to your template, and have the
  65. template output the commas in a :ttag:`for` loop.
  66. Here's an example, which generates the same CSV file as above::
  67. from django.http import HttpResponse
  68. from django.template import loader, Context
  69. def some_view(request):
  70. # Create the HttpResponse object with the appropriate CSV header.
  71. response = HttpResponse(mimetype='text/csv')
  72. response['Content-Disposition'] = 'attachment; filename=somefilename.csv'
  73. # The data is hard-coded here, but you could load it from a database or
  74. # some other source.
  75. csv_data = (
  76. ('First row', 'Foo', 'Bar', 'Baz'),
  77. ('Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"),
  78. )
  79. t = loader.get_template('my_template_name.txt')
  80. c = Context({
  81. 'data': csv_data,
  82. })
  83. response.write(t.render(c))
  84. return response
  85. The only difference between this example and the previous example is that this
  86. one uses template loading instead of the CSV module. The rest of the code --
  87. such as the ``mimetype='text/csv'`` -- is the same.
  88. Then, create the template ``my_template_name.txt``, with this template code:
  89. .. code-block:: html+django
  90. {% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes }}"
  91. {% endfor %}
  92. This template is quite basic. It just iterates over the given data and displays
  93. a line of CSV for each row. It uses the :tfilter:`addslashes` template filter to
  94. ensure there aren't any problems with quotes.
  95. Other text-based formats
  96. ========================
  97. Notice that there isn't very much specific to CSV here -- just the specific
  98. output format. You can use either of these techniques to output any text-based
  99. format you can dream of. You can also use a similar technique to generate
  100. arbitrary binary data; see :doc:`/howto/outputting-pdf` for an example.