暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

【Django】admin+simpleUI应用配置

一生之记 2022-07-14
4774

一、增加【导入】【导出】

1、首先安装

    pip install django-import-export

    2、在settings.py文件添加到INSTALLED_APPS 里面

      # settings.py
      INSTALLED_APPS = (
      ...
      'import_export',
      )

      3、admin.py配置



      • ‘导入’和‘导出’:

        ImportExportModelAdmin&ImportExportActionModelAdmin(建议使用)

      • 只‘导入’不‘导出’:ImportMixin

      • 只‘导出’不‘导入’:ExportMixin

      4、自定义导入导出字段,调整字段顺序

      • 新建‘resource.py’

      • 示例


        • # resource.py
          from import_export import resources
          from app_spider.models import gitlab_name

          class BookResource(resources.ModelResource):
          class Meta:
          # 对应models的类
          model = gitlab_name
          # fields是指定哪些字段须要导入
          fields = ('id', 'name', 'author', 'price',)
          # export_order是导出的字段顺序
          export_order = ('id', 'price', 'author', 'name')


        5、在admin类里面进行调用

        • #admin.py

        ⚠️注意:因设置自定义按钮会导致导出按钮被隐藏:按以下写法进行拼接即可展示



        二、自定义按钮设置

          # admin.py
          # 增加自定义按钮
          actions = ['button_exeScript', ]


          # 按钮方法
          def button_exeScript(self, request, queryset):
          """按钮逻辑编写"""
          response = HttpResponse(content_type="application/json")
          # 获取序列化数据
          fields = serializers.serialize("json", queryset, stream=response)
          print(fields)
          # 将 JSON 对象转换为 Python 字典
          fields1 = json.loads(fields)


          # 勾选多条数据时候,可进行多条数据执行
          for field in fields1:
          # 获取有用的数据
          fk_project_id = field["fields"]["fk_project"]
          milestone_name = field["fields"]["milestone_name"]
          milestone_username = field["fields"]["milestone_username"]
          # 获取当前时间
          CreatTime = time.strftime("%Y-%m-%d", time.localtime())
          # 获取当前登陆用户名
          CreatUser = request.user
          print(fk_project_id, milestone_name, milestone_username, CreatTime, CreatUser)


          # 自定义提示语
          messages.add_message(request, messages.INFO, '执行成功')
          # 返回数据
          # return fk_project_id, milestone_name, milestone_username
          ----------------- 列表页按钮样式使用---------------------
          # 给按钮增加确认
          button_exeScript.confirm = '点击确认,将获取milestone相关人员的BUG数据'
          # 设置按钮名称
          button_exeScript.short_description = '执行数据'


          # icon,参考element-ui icon与https://fontawesome.com
          button_exeScript.icon = 'fas el-icon-position'


          # 指定element-ui的按钮类型,参考https://element.eleme.cn/#/zh-CN/component/button
          button_exeScript.type = 'danger'


          # 给按钮追加自定义的颜色
          button_exeScript.style = 'color:#f8f8f8;border-color:#1db393;background-color:#1db393;'
          # 按钮动作类型,0=当前页内打开,1=新tab打开,2=浏览器tab打开
          # button_exeScript.action_type = 0
          # 按钮跳转地址
          # button_exeScript.action_url = '0'
          ----------------- layer的使用(自定义表单样式)---------------------
          # 指定为弹出层,这个参数最关键:需要导入(from simpleui.admin import AjaxAdmin),对应admin类进行继承AjaxAdmin
          button_exeScript.layer = {
                  # 弹出层中的输入框配置
          # 这里指定对话框的标题
          'title': '弹出层输入框',
          # 提示信息
          'tips': '这个弹出对话框是需要在admin中进行定义,数据新增编辑等功能,需要自己来实现。',
          # 确认按钮显示文本
          'confirm_button': '确认提交',
          # 取消按钮显示文本
          'cancel_button': '取消',


          # 弹出层对话框的宽度,默认50%
          'width': '40%',


          # 表单中 label的宽度,对应element-ui的 label-width,默认80px
          'labelWidth': "80px",
          'params': [{
          # 这里的type 对应el-input的原生input属性,默认为input
          'type': 'input',
          # key 对应post参数中的key
          'key': 'name',
          # 显示的文本
          'label': '名称',
          # 为空校验,默认为False
          'require': True
          }, {
          'type': 'select',
          'key': 'type',
          'label': '类型',
          'width': '200px',
          # size对应elementui的size,取值为:medium small mini
          'size': 'small',
          # value字段可以指定默认值
          'value': '0',
          'options': [{
          'key': '0',
          'label': '收入'
          }, {
          'key': '1',
          'label': '支出'
          }]
          }, {
          'type': 'number',
          'key': 'money',
          'label': '金额',
          # 设置默认值
          'value': 1000
          }, {
          'type': 'date',
          'key': 'date',
          'label': '日期',
          }, {
          'type': 'datetime',
          'key': 'datetime',
          'label': '时间',
          }, {
          'type': 'rate',
          'key': 'star',
          'label': '评价等级'
          }, {
          'type': 'color',
          'key': 'color',
          'label': '颜色'
          }, {
          'type': 'slider',
          'key': 'slider',
          'label': '滑块'
          }, {
          'type': 'switch',
          'key': 'switch',
          'label': 'switch开关'
          }, {
          'type': 'input_number',
          'key': 'input_number',
          'label': 'input number'
          }, {
          'type': 'checkbox',
          'key': 'checkbox',
          # 必须指定默认值
          'value': [],
          'label': '复选框',
          'options': [{
          'key': '0',
          'label': '收入'
          }, {
          'key': '1',
          'label': '支出'
          }, {
          'key': '2',
          'label': '收益'
          }]
          }, {
          'type': 'radio',
          'key': 'radio',
          'label': '单选框',
          'options': [{
          'key': '0',
          'label': '收入'
          }, {
          'key': '1',
          'label': '支出'
          }, {
          'key': '2',
          'label': '收益'
          }]
          }]
          }

          三、隐藏按钮

            # 禁用列表页面的按钮
            # admin.py 放入对应admin类中
            def has_add_permission(self, request):
            """禁用添加按钮"""
            return False


            def has_delete_permission(self, request, obj=None):
            """禁用删除按钮"""
            return False
            # 禁用编辑链接
            list_display_links = None

            四、admin页面基本字段编辑

              class ProjectAdmin(admin.ModelAdmin):
              ----------------- 筛选器---------------------
              # list_filter筛选条件
              list_filter = ['name', 'method', 'url', 'UpdateUser']


              # date_hierarchy详细时间分层筛选
              date_hierarchy = 'cre_date'


              # 自定义搜索选项search_field(注意search_field只能用于CharField或TextField。)
              search_fields = ['milestone_name']


              ----------------列表基本设置-------------------
              # list_per_page分页:设置每页显示多少条记录,默认是100条
              list_per_page = 20


              # actions_on_top增加一个底部的删除选项
              actions_on_top = False


              # actions_on_bottom将上面的删除操作选项关了
              actions_on_bottom = False


              # fieldsets控制新增页面
              fieldsets = [('执行任务', {'fields': ['name', 'headers', 'method', 'url', 'data']}),
              ('选择调度器(注意:只能选择其中一个调度器进行执行,否则会报错)', {'fields': ['interval', 'cron', 'date']})]

              # listdisplay设置要显示在列表中的字段(id字段是Django模型的默认主键)
              list_display = ['id', 'project_name', 'description', 'project_type', 'project_status', 'cre_date']


              # list_display_links表示可点击跳转进入详情的字段(默认可以点击每条记录第一个字段的值可以进入编辑界面)
              list_display_links = ('id', 'project_name')


              # list_editable表示可直接在列表也编辑修改的字段
              list_editable = ['description', 'project_type', 'project_status']


              # ordering设置默认排序字段,负号表示降序排序
              ordering = ('-cre_date',)


              # 此属性将覆盖记录字段为空(None,空字符串等)的默认显示值(默认值为-) 字符串
              empty_value_display = " "
              ----------------- 表关联---------------------
              # filter_horizontal多键关联-新增页面样式
              filter_horizontal = ('milestone_username',)


              文章转载自一生之记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

              评论