在管理员中向 Django 的 export_as_csv 操作添加动态字段
Posted
技术标签:
【中文标题】在管理员中向 Django 的 export_as_csv 操作添加动态字段【英文标题】:Adding dynamic fields to Django's export_as_csv action in admin 【发布时间】:2015-02-06 03:31:07 【问题描述】:我正在尝试自定义出现在管理菜单中的export_as_csv
操作,以便可以将动态字段添加到导出的 CSV 文件中。这是通过使用提供Export as CSV 操作的django-adminactions。到目前为止,我有以下内容:
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
函数添加动态字段?
【问题讨论】:
“动态字段”是什么意思? 【参考方案1】:您必须将调用包装在可调用对象中,但仅在操作中声明名称:
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]
【讨论】:
【参考方案2】:这是我不久前做的:
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
【讨论】:
以上是关于在管理员中向 Django 的 export_as_csv 操作添加动态字段的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Django 中向 bootstrap4 添加松脆的表单?
如何在 Django 中向 ManyToManyField 添加条目?
在 django 中向新的***域 (TLD) 发送电子邮件