Login

Non model specific CSV export of database content

Author:
sethtrain
Posted:
February 9, 2008
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 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.