五、xadmin自定义插件2

以导入插件为例说明:

  1、在xadmin-->plugins下面新建excel.py文件

  2、新建ListExcelImportPlugin类,继承BaseAdminPlugin

    from xadmin.views import BaseAdminPlugin, ListAdminView

    from django.template import loader

    import xadmin

    class ListExcelImportPlugin(BaseAdminPlugin):

      # 重写init_request

      import_excel = False

      def init_request(self, request, *args, **kwargs):

        return bool(self.import_excel)

    

      def block_top_toolbar(self, context, nodes):

        # 这里 xadmin/excel/model_list.top_toolbar.import.html 是自己写的html文件

        nodes.append(loader.render_to_string("xadmin/excel/model_list.top_toolbar.import.html"))

    xadmin.site.register_plugin(ListExcelImportPlugin, ListAdminView)

  3、在需要有导入插件的ModelAdmin中加入 import_excel = True

    并重写post函数

    def post(self, request, *args, **kwargs):

      if "excel" in request.FILES:

        #此处自定义逻辑,如读取文件保存数据库等

        pass

      return super(ModelAdmin, self).post(request, args, kwargs)

原文地址:https://www.cnblogs.com/fiona-zhong/p/9594167.html