Skip to content

Instantly share code, notes, and snippets.

@macielportugal
Last active June 1, 2018 19:33
Show Gist options
  • Save macielportugal/728db1d26e32689109da27f8dbd5c33e to your computer and use it in GitHub Desktop.
Save macielportugal/728db1d26e32689109da27f8dbd5c33e to your computer and use it in GitHub Desktop.
Action to export to csv in Django 2.0
# Action Export CSV to DJANGO 2.0
import csv
from django.http import HttpResponse
def export_csv(modeladmin, request, queryset):
response = HttpResponse(content_type="text/csv")
response['Content-Disposition'] = 'attachment; filename="export.csv"'
writer = csv.writer(response)
if hasattr(modeladmin, 'list_export'):
fields = modeladmin.list_export
else:
fields = modeladmin.list_display
if hasattr(modeladmin, 'head_export'):
head_export = getattr(modeladmin, 'head_export')
else:
head_export = True
if head_export:
head = []
for field in fields:
if field == '__str__':
verbose_name = queryset.model._meta.verbose_name
else:
verbose_name = queryset.model._meta.get_field(field).verbose_name
head.append(verbose_name)
writer.writerow(head)
for obj in queryset:
body = []
for field in fields:
if field == '__str__':
value = str(obj)
else:
value = getattr(obj, field)
if queryset.model._meta.get_field(field).choices:
value = '{} - {}'.format(value, getattr(obj, 'get_' + field + '_display')())
body.append(value)
writer.writerow(body)
return response
from django.contrib import admin
from .actions import export_csv
from .models import Foo
export_csv.short_description = 'Export CSV'
# Example 1
@admin.register(Foo)
class ModelAdmin(admin.ModelAdmin):
list_display = ['created_at', 'status', 'client']
actions = [export_csv]
# Example 2
@admin.register(Foo)
class ModelAdmin(admin.ModelAdmin):
list_display = ['created_at', 'status', 'client']
list_export = ['client']
actions = [export_csv]
# Example 3
@admin.register(Foo)
class ModelAdmin(admin.ModelAdmin):
actions = [export_csv]
head_export = False # Default is True
list_export = ['client']
# Example 4
# Global
admin.site.add_action(export_csv, 'export_csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment