在admin中为Django的export_as_csv操作添加动态字段

时间:2014-12-08 13:01:54

标签: django python-2.7 django-admin django-admin-actions

我尝试自定义管理菜单中显示的export_as_csv操作,以便我可以向导出的CSV文件添加动态字段。这是通过使用提供django-adminactions操作的Export as CSV。到目前为止,我有以下内容:

from django.contrib import admin
from adminactions.api import csv_options_default, export_as_csv as _export_as_csv
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):    
    list_display = ('field1', 'field2', 'field3')

    qs = MyModel.objects.all()
    options = csv_options_default
    fields = ['field4', 'field5']
    header = ['Header4', 'Header5']
    actions = [_export_as_csv(queryset=qs, fields=fields, header=header, options=options)]

admin.site.register(MyModel, MyModelAdmin)

但是上面的内容会在页面上生成错误,如下所示:

hasattr(): attribute name must be string
    Request Method: GET
    Request URL:    http://localhost:8000/admin/mymodel/mymodel/
    Django Version: 1.4.14
    Exception Type: TypeError
    Exception Value:    
    hasattr(): attribute name must be string
    Exception Location: /home/me/.virtualenvs/myproj/local/lib/python2.7/site-packages/django/contrib/admin/options.py in get_action, line 648
    Python Executable:  /home/me/.virtualenvs/myproj/bin/python
    Python Version: 2.7.6

我是以正确的方式做到这一点的吗?如何在管理员中为Django的export_as_csv函数添加动态字段?

2 个答案:

答案 0 :(得分:0)

我做了一会儿:

https://djangosnippets.org/snippets/2995/

可以像这样使用:

class ExampleModelAdmin(admin.ModelAdmin):
    raw_id_fields = ('field1',)
    list_display = ('field1', 'field2', 'field3',)
    actions = [download_as_csv("Export Special Report"),]  # custom label for action
    download_as_csv_fields = [
        'field1',  # will use Django field verbose_name as col name
        ('foreign_key1__foreign_key2__name', 'label2'),  # traverse relations with __ syntax
        ('field3', 'label3'),  # custom col name
    ],
    download_as_csv_header = True  # output a header row in the csv

答案 1 :(得分:0)

你必须以可调用的方式包含你的电话,但只在你的行动中声明你的名字:

from adminactions.api import export_as_csv as _export_as_csv

def my_export_as_csv(modeladmin, request, queryset):
    return _export_as_csv(modeladmin.qs, 
                          fields=modeladmin.fields, 
                          header=modeladmin.header, 
                          filename=None, 
                          options=modeladmin.options, 
                          out=None)


class MyModelAdmin(admin.ModelAdmin):    
    list_display = ('field1', 'field2', 'field3')

    qs = MyModel.objects.all()
    options = csv_options_default
    fields = ['field4', 'field5']
    header = ['Header4', 'Header5']
    actions = [my_export_as_csv]