Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If the file is <strong>static</strong> (i.e not generated specifically for this request) you shouldn't be serving it through django anyway. You should configure some path (like /static/) to be served by your webserver, and save all the django overhead.</p> <p>If the file is <strong>dynamic</strong>, there are 2 options: </p> <ol> <li>Create it in memory and serve it from django.</li> <li>Create it on the disk, and return a HttpResponseRedirect to it, so that your webserver deals with the download itself (if the file is very large, you should use this option).</li> </ol> <p>As for serving it dynamically, I've been using the following code (which is a simplified version of <a href="http://www.djangosnippets.org/snippets/1151/" rel="nofollow noreferrer">ExcelResponse</a>)</p> <pre><code>import StringIO from django.db.models.query import ValuesQuerySet, QuerySet class CSVResponse(HttpResponse): def __init__(self, data, output_name='data', headers=None, encoding='utf8'): # Make sure we've got the right type of data to work with valid_data = False if isinstance(data, ValuesQuerySet): data = list(data) elif isinstance(data, QuerySet): data = list(data.values()) if hasattr(data, '__getitem__'): if isinstance(data[0], dict): if headers is None: headers = data[0].keys() data = [[row[col] for col in headers] for row in data] data.insert(0, headers) if hasattr(data[0], '__getitem__'): valid_data = True assert valid_data is True, "CSVResponse requires a sequence of sequences" output = StringIO.StringIO() for row in data: out_row = [] for value in row: if not isinstance(value, basestring): value = unicode(value) value = value.encode(encoding) out_row.append(value.replace('"', '""')) output.write('"%s"\n' % '","'.join(out_row)) mimetype = 'text/csv' file_ext = 'csv' output.seek(0) super(CSVResponse, self).__init__(content=output.getvalue(), mimetype=mimetype) self['Content-Disposition'] = 'attachment;filename="%s.%s"' % \ (output_name.replace('"', '\"'), file_ext) </code></pre> <p>To use it, just use return CSVResponse(...) passing in a list of lists, a list of dicts (with same keys), a QuerySet, a ValuesQuerySet</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload