Created
November 24, 2015 21:47
-
-
Save jeremyjbowers/e8d007446155c12033e6 to your computer and use it in GitHub Desktop.
Export to CSV for Django admin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
from django.http import HttpResponse | |
def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): | |
""" | |
This function returns an export csv action | |
'fields' and 'exclude' work like in django ModelForm | |
'header' is whether or not to output the column names as the first row | |
""" | |
def export_as_csv(modeladmin, request, queryset): | |
""" | |
Generic csv export admin action. | |
based on http://djangosnippets.org/snippets/1697/ | |
""" | |
opts = modeladmin.model._meta | |
field_names = set([field.name for field in opts.fields]) | |
if fields: | |
fieldset = set(fields) | |
field_names = field_names & fieldset | |
elif exclude: | |
excludeset = set(exclude) | |
field_names = field_names - excludeset | |
response = HttpResponse(content_type='text/csv') | |
response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_') | |
writer = csv.writer(response) | |
if header: | |
writer.writerow(list(field_names)) | |
for obj in queryset: | |
writer.writerow([unicode(getattr(obj, field)).encode("utf-8","replace") for field in field_names]) | |
return response | |
export_as_csv.short_description = description | |
return export_as_csv |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import admin | |
from actions import export_as_csv_action | |
class CaseAdmin(admin.ModelAdmin): | |
... | |
actions = [export_as_csv_action("CSV Export", fields=['field1', 'field2'])] |
Hello,
In your models.py file, the model that your foreign key references must have a function:
def __str__(self):
return self.name_to_be_displayed
Example
class School(models.Model):
school_name = models.CharField(max_length=55)
def __str__(self):
return self.school_name
class Student(models.Model):
name = models.CharField(max_length=25)
school = models.ForeignKey(School, models.DO_NOTHING)
And in your admin.py, you can do this:
class StudentAdmin(admin.ModelAdmin):
...
actions = [export_as_csv_action("CSV Export", fields=['name', 'school'])]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello. I would like to use this csv export format because is so nice. It's working properly, but I can't get solution, how can get foreign key value to export. Have you any idea?Thanks.