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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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
#
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.
#
Was that supposed to be a link?!? :-S
#
No that is suppose to be a folder structure....sorry should be:
#
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!
#
Awesome code, I ended up using it for snippet 790 (which has code to integrate with the admin interface)
#
Please login first before commenting.