Login

Non model specific CSV export of database content

Author:
sethtrain
Posted:
February 9, 2008
Language:
Python
Version:
.96
Tags:
export csv
Score:
4 (after 4 ratings)

When given a model this utility method will export all data in that model to a CSV file. I use this method to place an "Export" button on a particular model's change list page in the Django administrator.

 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 2 years, 2 months ago
  2. Generic admin action to export data into excel/csv by vinay.chittora 1 year, 11 months ago
  3. export to csv, import from csv by peiwei 2 years ago
  4. Admin action for a "CSV Export" with ManyToManyField by CarlosRodriguez 1 year ago
  5. CSV Exporting of Model Data by monokrome 5 years, 7 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)

#

Please login first before commenting.