user2028720
user2028720

Reputation: 33

How to add custom function to Django admin?

How to use this code in admin.py in Django project? http://djangosnippets.org/snippets/2834/

I don't know how to add this function to my admin.ModelAdmin class

from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from pyExcelerator import *
from StringIO import StringIO


def export_as_xls(modeladmin, request, queryset):
    """
    Generic xls export admin action.
    """
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta

    wb = Workbook()
    ws0 = wb.add_sheet('0')
    col = 0
    field_names = []
    # write header row
    for field in opts.fields:
        ws0.write(0, col, field.name)
        field_names.append(field.name)
        col = col + 1

    row = 1
    # Write data rows
    for obj in queryset:
        col = 0
        for field in field_names:
            val = unicode(getattr(obj, field)).strip()
            ws0.write(row, col, val)
            col = col + 1
        row = row + 1   

    f = StringIO()
    wb.save(f)
    f.seek(0)
    response = HttpResponse(f.read(), mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(opts).replace('.', '_')
    return response

export_as_xls.short_description = "Export selected objects to XLS"

I tried different solutions, but failed to

Upvotes: 2

Views: 9560

Answers (2)

tim
tim

Reputation: 1482

Add it site wide

from django.contrib import admin

admin.site.add_action(export_as_xls)

Upvotes: 1

Aamir Rind
Aamir Rind

Reputation: 39689

lets say the snippet named as actions.py, then in admin.py do:

from myproject.actions import export_as_xls

class MyAdmin(admin.ModelAdmin):
    actions = [export_as_xls]

This is also mentioned in the snippet that how you have to use it.

Upvotes: 4

Related Questions