Xadmin添加插件——actions插件

目录

一、创建action.py文件

1.给action一个名字action_name;

2.给action一个描述description;

3.给action一个权限model_perm,权限就是queryset的add,delete,change,view;

4.给action一个图标icon,此图标可以使用Font Awesome图标;

5.给action一个执行函数do_action;

6.self和queryset的灵活使用

二、adminx.py引用插件


actions插件刚开始感觉不是很容易实现,放弃了很长一段时间,最近从新整理了下思路,已经能够实现对数据操作。(注:这里的数据是通过选项框选中案件,格式为queryset,此queryset是通过mysql语句通过id从数据库中查询得来,详情可以打印'print(queryset.query)')。

此插件常用作批量操作,生成excel、word文件等。

一、创建action.py文件

我们将要写的action需要继承BaseActionView,是xadmin的函数

from xadmin.plugins.actions import BaseActionView

1.给action一个名字action_name;

2.给action一个描述description;

3.给action一个权限model_perm,权限就是queryset的add,delete,change,view;

4.给action一个图标icon,此图标可以使用Font Awesome图标;

5.给action一个执行函数do_action;

以上5项就是一个完整的action了,其中1和2最终显示在xadmin的列表页,也就是action的显示位置。

 一个完整的action.py文件如下:

import os
import io
import xlwt,xlsxwriter
from docxtpl import DocxTemplate,InlineImage

from django.db.models import Count
from django.http import HttpResponse, HttpResponseRedirect

from SmallOA.settings import MEDIA_ROOT,MEDIA_URL,BASE_DIR
from xadmin.plugins.actions import BaseActionView


class Dd_TodailyAction(BaseActionView):
    action_name = 'export_word_dd'  # 随便起个名字
    description = u'批量案件生成报告'  # 页面中显示的操作名字
    model_perm = 'view'   #执行action需要的权限,其他的还有change,delete,add
    def do_action(self, queryset):
        # 获取当前文件的目录
        cur_path = os.path.abspath(os.path.dirname(__file__))
        #print(cur_path)
        # 获取根目录
        asset_url = cur_path + '\\' + '现场组监理简报.docx'
        tpl = DocxTemplate(asset_url)

        context = {}

        context['year'] = queryset.first().start_time.strftime("%Y")#年

        #生成可在word中使用的数据
        excel_row = 0#表格的行数
        question_list = []
        for obj in check:
            excel_row = excel_row + 1
            cont = {'number': excel_row,
                    'cols': str(obj.street) + '-' + str(obj.community) + '-' + str(obj.address) + '-' + str(obj.big.big) + '-' + str(obj.small.small) + '-' + str(obj.task_id),
                    'img_far': get_imgorstr(tpl,obj.img_far,100,125),
                    'img_near': get_imgorstr(tpl,obj.img_near,100,125),
                    'img_consult': get_imgorstr(tpl,obj.img_consult,100,125),
                    'state': obj.get_state_display(),
                    'ranks': get_rank(obj.ranks),
                 }
            question_list.append(cont)
        context['excel_row'] = excel_row
        context['question_list'] = question_list

        tpl.render(context)

        sio = io.BytesIO()
        tpl.save(sio)
        sio.seek(0)

        response = HttpResponse(sio.getvalue(), content_type=' application/msword')
        response['Content-Disposition'] = 'attachment; filename="{0}月{1}{2}"'.format(context['month'],context['day'] ,'日现场组监理简报.docx').encode('utf-8', 'ISO-8859-1')
        response.write(sio.getvalue())

        return response

6.self和queryset的灵活使用

二、adminx.py引用插件

此处简写

import xadmin
from xadmin.layout import Fieldset,Row
from datetime import datetime,timedelta

from .action import Dd_TodailyAction


class CheckAdmin(object):
    #form = Scene_dudao_Form
    list_display = ['task_id','problem_point','street','community','address','big','small','state','finishname','start_time','checkname',]
    list_filter = ['start_time','big','small','state','finishtime','checkname']
    search_fields = ['address','task_id']
    show_detail_fields =['task_id']
    list_per_page =10
    show_all_rel_details = False  # 不显示信息
    exclude = ['state_branch']  # 不显示字段
    list_editable = ['community','big']#列表页可编辑

    actions = [Dd_TodailyAction]#action插件
    show_bookmarks = True
    list_bookmarks = [
        {
        'title': "昨天",         # 书签的名称, 显示在书签菜单中
        'query': {'start_time__gte':datetime(datetime.now().year,datetime.now().month,datetime.now().day)-timedelta(days=1),
                  'start_time__lt':datetime(datetime.now().year,datetime.now().month,datetime.now().day)}, # 过滤参数, 是标准的 queryset 过滤
        'cols': ('task_id','problem_point','street','community','address','big','small','state','finishname','start_time','checkname'),  # 显示的列
        },
        {
        'title': "今天",  # 书签的名称, 显示在书签菜单中
        'query': {'start_time__gte': datetime(datetime.now().year, datetime.now().month, datetime.now().day),
                  'start_time__lt': datetime(datetime.now().year, datetime.now().month, datetime.now().day)+timedelta(days=1)},# 过滤参数, 是标准的 queryset 过滤
        'cols': ('task_id', 'problem_point', 'street', 'community', 'address', 'big', 'small', 'state', 'finishname','start_time', 'checkname'),  # 显示的列
        },
    ]

    form_layout = (
                Fieldset(u'基本信息',
                         Row('task_id'),
                         Row('street','community','address'),
                         Row('big', 'small')),
                Fieldset(u'图片',
                         Row('img_far','img_near','img_consult')),
                Fieldset(u'处置情况',
                         Row('state', 'ranks', 'finishtime')),
                )

Guess you like

Origin blog.csdn.net/qq_15028721/article/details/119029205