【问题标题】:How to add custom function to Django admin?如何向 Django 管理员添加自定义功能?
【发布时间】:2013-02-01 20:07:15
【问题描述】:

如何在 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"

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

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    假设sn-p 命名为actions.py,然后在admin.py 中执行:

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

    这在sn-p中也提到了你必须如何使用它。

    【讨论】:

      【解决方案2】:

      在网站范围内添加它

      from django.contrib import admin
      
      admin.site.add_action(export_as_xls)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-06
        • 2018-07-15
        • 2015-11-15
        • 1970-01-01
        • 1970-01-01
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多