django后台admin csv 格式表格导出
Posted wangruwei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django后台admin csv 格式表格导出相关的知识,希望对你有一定的参考价值。
1.在app下新建一个.py文件 此例commen.py
commen.py (内容)(具体怎么导出的也不知道这么写就对了)
import csv
from django.http import HttpResponse
def export_as_csv_action(description=‘Export selected objects as csv file‘,
fields=None,exclude=None,header=True):
def export_as_csv(modeladmin,request,queryset):
opts=modeladmin.model._meta
if not fields:
field_names=[field for field in opts]
else:
field_names=fields
response = HttpResponse( content_type = ‘text/csv‘)
response[‘Content-Disposition‘]=‘attachment;filename={}.csv‘.format(opts.verbose_name.encode(‘utf-8‘))
writer = csv.writer(response)
if header:
writer.writerow(field_names)
for obj in queryset:
# 正常的这样处理就行了
row = [getattr(obj,field)()if callable(getattr(obj,field))else getattr(obj,field) for field in field_names]
# 如果新添处理功能比如处理下时间的显示格式
# row=[]
# forfieldinfield_names:
# value=getattr(obj,field)
# ifisinstance(value,datetime.datetime):
# value=value.‘WW^sY‘)
# row.append(value)
writer.writerow(row)
return response
export_as_csv.short_description = description
return export_as_csv
2.在app下的admin.py
(1)导入刚才封装的函数
from .commen import export_as_csv_action
(2)如下操作
@admin.register(ECS)
class BlogAdmin(admin.ModelAdmin):
list_display=( ‘name‘,‘type‘,‘outer_net‘, ‘inner_mesh‘, ‘configure‘,‘strip_width‘,‘account_number‘,‘password‘,‘group‘,‘aliyun‘,‘expire_date‘,‘state‘)
list_per_page = 30
actions=[export_as_csv_action("导出Execl",fields=[‘name‘,‘type‘,‘outer_net‘, ‘inner_mesh‘, ‘configure‘,‘strip_width‘,‘account_number‘,‘password‘,‘group‘,‘aliyun‘,‘expire_date‘,‘state‘])]
search_fields =(‘name‘,‘type‘,‘outer_net‘, ‘inner_mesh‘, ‘configure‘,‘strip_width‘,‘account_number‘,‘password‘,‘group‘,‘aliyun‘,‘expire_date‘)
date_hierarchy = "expire_date"
以上是关于django后台admin csv 格式表格导出的主要内容,如果未能解决你的问题,请参考以下文章