码迷,mamicode.com
首页 > 其他好文 > 详细

admin组件扩展

时间:2020-05-14 17:35:51      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:script   ready   manager   rtc   osi   only   from   self   set   

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组件扩展

标签:script   ready   manager   rtc   osi   only   from   self   set   

原文地址:https://www.cnblogs.com/shaozheng/p/12889857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!