joshourisman / django-tablib

django-tablib is a helper library for Django that allows Django models to be used to generate tablib datasets with introspection of the fields on the models if no headers are provided. If headers are provided they can reference any attribute, fields, properties, or methods on the model.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

admin actions integration

ouhouhsami opened this issue · comments

hello,

Great app ;). Here is a snippet to integrate tab export inside admin actions, so that you can use django admin filters, and get an export only for instances in change list which are selected.

from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django_tablib.datasets import SimpleDataset
from django_tablib.base import mimetype_map

def xls_export(modeladmin, request, queryset):
    dataset = SimpleDataset(queryset, headers=None)
    filename = 'export.xls'
    response = HttpResponse(
        getattr(dataset, 'xls'),
        mimetype=mimetype_map.get('xls', 'application/octet-stream')
        )
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response
xls_export.short_description = "Excel export"

and just add xls_export to the actions list in your ModelAdmin.

It seems to me

  • easier than using TablibAdmin (I have allready custom buttons, so that I would have to override change_list)
  • more efficient as you can pre-filter your export
  • more user friendly

Thx

Hey, this is great! I'll definitely include this. Thanks!

I made a couple of minor adjustments to simplify multiple format support:

from django.http import HttpResponse
from django.utils.encoding import smart_str
from django.utils.translation import ugettext as _

from django_tablib.datasets import SimpleDataset
from django_tablib.base import mimetype_map

def tablib_export_action(modeladmin, request, queryset, format="xls"):
    """
    Allow the user to download the current filtered list of items

    :param format:
        One of the formats supported by tablib (e.g. "xls", "csv", "html", etc.)
    """

    dataset = SimpleDataset(queryset, headers=None)
    filename = '%s.%s' % (smart_str(modeladmin.model._meta.verbose_name_plural),
                          format)
    response = HttpResponse(getattr(dataset, format),
                            mimetype=mimetype_map.get(format,
                                                      'application/octet-stream'))
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response


def xls_export_action(*args, **kwargs):
    return tablib_export_action(format="xls", *args, **kwargs)
xls_export_action.__doc__ = tablib_export_action.__doc__
xls_export_action.short_description = _("Export to Excel")


def csv_export_action(*args, **kwargs):
    return tablib_export_action(format="csv", *args, **kwargs)
csv_export_action.__doc__ = tablib_export_action.__doc__
csv_export_action.short_description = _("Export to CSV")```