admin组件扩展
Posted shaozheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了admin组件扩展相关的知识,希望对你有一定的参考价值。
admin 扩展
admin 添加csv 功能:
import csv
from django.contrib import admin
from django.http import HttpResponse
from .models import Issue
class ExportCsvMixin(object):
def export_as_csv(self, request, queryset):
meta = self.model._meta
field_names = [field.name for field in meta.fields]
response = HttpResponse(content_type=‘text/csv‘)
response[‘Content-Disposition‘] = f‘attachment; filename={meta}.csv‘
response.charset = ‘utf-8-sig‘
writer = csv.writer(response)
writer.writerow(field_names)
for obj in queryset:
row = writer.writerow([getattr(obj, field) for field in field_names])
return response
export_as_csv.short_description = ‘导出CSV‘
@admin.register(Issue)
class IssueAdmin(admin.ModelAdmin, ExportCsvMixin):
fields = (‘key‘, ‘summary‘, ‘status‘, ‘project‘,
‘origin‘, ‘components‘, ‘prj_level‘, ‘prj_category‘,
‘assignee‘, ‘origin_person‘, ‘pm‘, ‘dev_manager‘, ‘test_manager‘, ‘tester‘, ‘fe_dev‘, ‘backend_dev‘,
‘plan_begin‘, ‘plan_end‘, ‘fe_plan_begin‘, ‘fe_plan_end‘, ‘test_plan_begin‘,
‘test_plan_end‘, ‘backend_plan_begin‘, ‘backend_plan_end‘,
‘created‘, ‘reopen‘, ‘prd_begin‘, ‘prd_end‘, ‘dev_begin‘, ‘dev_end‘,
‘test_begin‘, ‘test_end‘, ‘pm_check‘, ‘ready‘, ‘pause‘, ‘done‘,
‘pm_take‘, ‘dev_take‘, ‘test_take‘, ‘total_take‘,
‘tags‘,
)
readonly_fields = fields
list_display = (‘key‘, ‘summary‘, ‘status‘, ‘origin‘, ‘components‘, ‘created‘, ‘visit‘)
list_filter = (‘origin‘, ‘components‘, ‘status‘, ‘tags‘)
search_fields = (‘key‘, ‘summary‘)
date_hierarchy = ‘created‘
actions = [‘export_as_csv‘]
admin 添加 excel 功能:
class ExportExcelMixin(object):
def export_as_excel(self, request, queryset):
meta = self.model._meta
field_names = [field.name for field in meta.fields]
response = HttpResponse(content_type=‘application/msexcel‘)
response[‘Content-Disposition‘] = f‘attachment; filename={meta}.xlsx‘
wb = Workbook()
ws = wb.active
ws.append(field_names)
for obj in queryset:
for field in field_names:
data = [f‘{getattr(obj, field)}‘ for field in field_names]
row = ws.append(data)
wb.save(response)
return response
export_as_excel.short_description = ‘导出Excel‘
以上是关于admin组件扩展的主要内容,如果未能解决你的问题,请参考以下文章
Django admin 组件 原理分析与扩展使用 之 sites.py
如何使用新的导航架构组件从扩展 BroadcastReceiver 的类导航到片段