Non model specific CSV export of database content

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import csv
from django.http import HttpResponse
from django.template.defaultfilters import slugify

def export(model):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % slugify(model.__name__)
    writer = csv.writer(response)
    # Write headers to CSV file
    headers = []
    for field in model._meta.fields:
        headers.append(field.name)
    writer.writerow(headers)
    # Write data to CSV file
    print model.objects.all()
    for obj in model.objects.all().order_by("id"):
        row = []
        for field in model._meta.fields:
            row.append(getattr(obj, field.name))
        writer.writerow(row)
    # Return CSV file to browser as download
    return response

More like this

  1. Django Admin CSV Export Mixin by Ceran 1 year ago
  2. Generic admin action to export data into excel/csv by vinay.chittora 8 months, 2 weeks ago
  3. export to csv, import from csv by peiwei 10 months ago
  4. CSV Exporting of Model Data by monokrome 4 years, 5 months ago
  5. CSV Exporting of Model Data by monokrome 4 years, 5 months ago

Comments

aj (on February 12, 2008):

hey - nice snippet. i can't help wondering how you're getting the 'export' button onto the admin pages? been trying to do something similar and haven't found an easy or elegant way. :( aj

#

sethtrain (on February 12, 2008):

So for a Page model here is my template folder structure:

/templates/admin/app/pagechange_list.html

In that file I have just copied and pasted the normal object-tools block and added a couple of list items before the main one available.

#

aj (on February 12, 2008):

Was that supposed to be a link?!? :-S

#

sethtrain (on February 12, 2008):

No that is suppose to be a folder structure....sorry should be:

/templates
    /admin
         /app (change to app name)
             /model (change to model name)
                 change_list.html

#

aj (on February 13, 2008):

Ah - I see your point. :)

Would it be possible to see the change_list.html template file? Perhaps easiest by email - mine is aj * cubbyhole _ net.

Much appreciated!

#

zbyte64 (on June 10, 2008):

Awesome code, I ended up using it for snippet 790 (which has code to integrate with the admin interface)

#

(Forgotten your password?)