Django admin后台添加自定义菜单和功能页面

ops/2024/10/22 8:11:41/

django admin是根据注册的模型来动态生成菜单,从这个思路出发,如果想添加自定义菜单,那就创建一个空模型并且注册。步骤如下:

1、创建空模型:

class ResetSVNAuthFileModel(models.Model):"""仅用来显示一个菜单"""class Meta:verbose_name = '重置授权文件'verbose_name_plural = verbose_name

2、注册到admin.py

重写changelist_view函数,使其点击菜单时,展示自定义的页面。在此你可以做orm查询,并且将数据渲染到模板中。而我想实现的是在页面中点击一个按钮来触发请求后端接口,来实现某种行为。

from django.contrib import admin
from django.shortcuts import renderfrom apps.setting.models import ResetSVNAuthFileModel@admin.register(ResetSVNAuthFileModel)
class FeedbackStatsAdmin(admin.ModelAdmin):def changelist_view(self, request, extra_content=None):template_name = 'reset_svn_auth_file.html'return render(request, template_name)
reset_svn_auth_file.html:
{% extends "admin/base_site.html" %}
{% load static %}{% block content %}<div class="text-center"><!-- 点击按钮调用 JavaScript 函数 --><button onclick="resetFunction()" id="resetButton" class="btn btn-primary btn-lg">重置授权文件</button></div>
{% endblock %}{% block extrahead %}<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script><script>function resetFunction() {// 禁用按钮document.getElementById("resetButton").disabled = true;// 发送 AJAX 请求到 Django 视图fetch('/admin-api/reset-auth-file').then(response => {if (response.ok) {Swal.fire({icon: 'success',title: 'OK',text: '操作成功',})} else {response.json().then(data => {console.log(data)Swal.fire({icon: 'error',title: '重置失败',text: data.msg,})})}}).catch((error) => {Swal.fire({icon: 'error',title: 'Oops...',text: '请求失败',})}).finally(() => {// 恢复按钮状态document.getElementById("resetButton").disabled = false;});}</script>
{% endblock %}

把该文件放在空模型所在app下的templates文件夹。

3、定义后端路由和接口

django总路由:

from django.contrib import admin
from django.urls import path, includefrom apps.repository.views import ResetAuthFileViewadmin_api = [path('reset-auth-file/', ResetAuthFileView.as_view(), name='reset-auth-file'),]urlpatterns = [path('admin/', admin.site.urls),path('admin-api/', include(admin_api)),  # 在admin 自定义页面中发送过来的请求
]

接口函数:

class ResetAuthFileView(APIView):def get(self, request):# 可以写个中间件做认证sessionid = request.COOKIES.get('sessionid')csrftoken = request.COOKIES.get('csrftoken')session = SessionStore(session_key=sessionid)if not session.exists(session_key=sessionid):return Response(status=401)try:SVN.reset_authz_file()except Exception as e:return Response(data={'msg': f'重置失败:{e}'}, status=400)return Response(data={'msg': '重置完成'})

大功告成,看成果:

点击菜单后的页面:


http://www.ppmy.cn/ops/5541.html

相关文章

I2C,UART,SPI(STM32、51单片机)

目录 基本理论知识&#xff1a; 并行通信/串行通信&#xff1a; 异步通信/同步通信&#xff1a; 半双工通信/全双工通信: UART串口&#xff1a; I2C串口&#xff1a; SPI串口&#xff1a; I2C在单片机中的应用&#xff1a; 软件模拟&#xff1a; 51单片机&#xff1a;…

Ubuntu上安装Chrome浏览器

安装步骤 1.下载安装chrome安装包 wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb2.安装Chrome浏览器 sudo dpkg -i google-chrome-stable_current_amd64.debsudo apt-get -f install3.启动Chrome浏览器 查看收藏夹里的Chrome图标 单击C…

2024 计算机毕业设计之SpringBoot+Vue项目合集(源码+L文+PPT)

各位朋友大家好&#xff0c;有幸与屏幕前你们相识&#xff0c;博主现已经搬砖9年&#xff0c;趁着头发还充裕&#xff0c;希望给大家提供一些编程领域的帮助&#xff0c;深知计算机毕业生这个阶段的崩溃与闹心&#xff0c;让我们共同交流进步。 博主给大家列举了项目合集&#…

Go语言异常处理方式

Go 语言没有传统的异常处理机制&#xff0c;如 Java、C 或 Python 中的 try-catch 语句。取而代之&#xff0c;Go 采用了基于返回错误值和 panic/recover 机制的混合模式来进行错误处理。以下是 Go 语言中处理异常&#xff08;或称错误&#xff09;的两种主要方式&#xff1a; …

Python的pytest框架(1)--基本概念、入门

按基础到进阶的顺序&#xff0c;学习Python的pytest框架&#xff0c;本篇文章先讲一讲pytest的基本概念、入门使用规则。 目录 一、pytest基础知识 1、安装 2、pytest框架主要做了什么工作 二、pytest的规则约定、运行方式以及参数详解 1、编写测试用例 模块&#xff08…

Linux CPU火焰图

Linux CPU火焰图 1、火焰图简介 火焰图&#xff08;Flame Graph&#xff09;是一种强大的性的性能分析工具&#xff0c;专门用于可视化cpu时间消耗咋各个函数栈上的情况&#xff0c;可以很快帮助开发这识别程序中的性能瓶颈和热点函数&#xff0c;从而有效的进行程序优化&…

Redis从入门到精通(二十二)Redis原理之数据结构、网络模型、通心协议、内存回收

文章目录 第8章 Redis原理8.1 Redis数据结构8.1.1 RedisObject8.1.2 动态字符串&#xff08;SDS&#xff09;8.1.3 string8.1.4 List8.1.5 Set8.1.6 ZSet8.1.7 Hash 8.2 Redis网络模型8.2.1 五种网络模型介绍8.2.1.1 用户空间和内核空间8.2.1.2 阻塞IO8.2.1.3 非阻塞IO8.2.1.4 …

OpenHarmony实战开发-如何使用弹簧曲线实现抖动动画及手机振动效果案例。

介绍 本示例介绍使用vibrator.startVibration方法实现手机振动效果&#xff0c;用keyframeAnimateTo关键帧动画实现点击后的抖动动画。 效果图预览 使用说明 1.加载完成后显示登录界面&#xff0c;未勾选协议时点击一键登录按钮会触发手机振动效果和提示文本的抖动动画。 实…