Skip to content

Instantly share code, notes, and snippets.

@michaelchiche
Forked from mgerring/actions.py
Created August 26, 2016 14:48
Show Gist options
  • Select an option

  • Save michaelchiche/933ff4bb238b8f30e91f371a7b42efd1 to your computer and use it in GitHub Desktop.

Select an option

Save michaelchiche/933ff4bb238b8f30e91f371a7b42efd1 to your computer and use it in GitHub Desktop.

Revisions

  1. @mgerring mgerring created this gist Sep 5, 2012.
    30 changes: 30 additions & 0 deletions actions.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    import unicodecsv
    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):
    opts = modeladmin.model._meta

    if not fields:
    field_names = [field.name for field in opts.fields]
    else:
    field_names = fields

    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=%s.csv' % unicode(opts).replace('.', '_')

    writer = unicodecsv.writer(response, encoding='utf-8')
    if header:
    writer.writerow(field_names)
    for obj in queryset:
    row = [getattr(obj, field)() if callable(getattr(obj, field)) else getattr(obj, field) for field in field_names]
    writer.writerow(row)
    return response
    export_as_csv.short_description = description
    return export_as_csv
    10 changes: 10 additions & 0 deletions admin.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    from django.contrib import admin
    from repsf.map.models import Location
    from django.http import HttpResponse, HttpResponseForbidden
    from actions import export_as_csv_action

    class SpamAdmin(admin.ModelAdmin):
    list_display = ['wink','nudge']
    actions = [export_as_csv_action("CSV Export", fields=['wink','nudge'])]

    admin.site.register(Location, LocationAdmin)