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

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

1、创建空模型:

python 复制代码
class ResetSVNAuthFileModel(models.Model):
    """仅用来显示一个菜单"""

    class Meta:
        verbose_name = '重置授权文件'
        verbose_name_plural = verbose_name

2、注册到admin.py

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

python 复制代码
from django.contrib import admin
from django.shortcuts import render

from 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:
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总路由:

python 复制代码
from django.contrib import admin
from django.urls import path, include

from apps.repository.views import ResetAuthFileView

admin_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 自定义页面中发送过来的请求
]

接口函数:

python 复制代码
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': '重置完成'})

大功告成,看成果:

点击菜单后的页面:

相关推荐
想摆烂的不会研究的研究生20 分钟前
每日八股——Redis(1)
数据库·经验分享·redis·后端·缓存
码熔burning31 分钟前
MySQL 8.0 新特性爆笑盘点:从青铜到王者的骚操作都在这儿了!(万字详解,建议收藏)
数据库·mysql
猫头虎38 分钟前
2025最新OpenEuler系统安装MySQL的详细教程
linux·服务器·数据库·sql·mysql·macos·openeuler
哈库纳玛塔塔1 小时前
放弃 MyBatis,拥抱新一代 Java 数据访问库
java·开发语言·数据库·mybatis·orm·dbvisitor
木子.李3471 小时前
ssh连接远程服务器相关总结
运维·服务器·ssh
BD_Marathon2 小时前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
@LetsTGBot搜索引擎机器人2 小时前
2025 Telegram 最新免费社工库机器人(LetsTG可[特殊字符])搭建指南(含 Python 脚本)
数据库·搜索引擎·机器人·开源·全文检索·facebook·twitter
计算机毕设VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue动物园管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
冉冰学姐3 小时前
SSM校园排球联赛管理系统y513u(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·ssm 框架应用·开题报告、
Tony Bai4 小时前
【分布式系统】03 复制(上):“权威中心”的秩序 —— 主从架构、一致性与权衡
大数据·数据库·分布式·架构