2

Django プロジェクトの admin.py でこのコードを使用するには? http://djangosnippets.org/snippets/2834/

この関数を 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"

さまざまな解決策を試しましたが、失敗しました

4

2 に答える 2

3

という名前のスニペットを言ってactions.pyadmin.pyましょう。

from myproject.actions import export_as_xls

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

これは、どのように使用する必要があるかというスニペットにも記載されています。

于 2013-02-01T20:12:14.833 に答える
1

サイト全体に追加する

from django.contrib import admin

admin.site.add_action(export_as_xls)
于 2017-12-12T04:55:10.163 に答える