如何向Django admin添加自定义函数?

如何向Django admin添加自定义函数?,django,django-admin,Django,Django Admin,如何在Django项目的admin.py中使用此代码? 我不知道如何将此函数添加到admin.ModelAdmin类中 from django.core.exceptions import PermissionDenied from django.http import HttpResponse from pyExcelerator import * from StringIO import StringIO def export_as_xls(modeladmin, request, q

如何在Django项目的admin.py中使用此代码?

我不知道如何将此函数添加到admin.ModelAdmin类中

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"

我尝试了不同的解决方案,但失败了

让我们假设名为
actions.py
的代码段,然后在
admin.py
中执行以下操作:

from myproject.actions import export_as_xls

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

这在代码段中也提到了如何使用它。

假设代码段名为
actions.py
,然后在
admin.py
中执行以下操作:

from myproject.actions import export_as_xls

class MyAdmin(admin.ModelAdmin):
    actions = [export_as_xls]
片段中还提到了如何使用它。

在站点范围内添加它 在站点范围内添加它