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': '重置完成'})

大功告成,看成果:

点击菜单后的页面:

相关推荐
SelectDB4 小时前
为什么 JSON 正在成为分析数据库新的竞争点?
数据库·json·agent
ClouGence5 小时前
开源数据库管理工具 CloudDM 4.2.0 发布,新增 GoldenDB、KingbaseES 等数据源
数据库·dba·devops
发霉的馒头5 小时前
ORA-00845: MEMORY_TARGET not supported on this system的解决方法
数据库
BreezeJiang6 小时前
从域名到 Node.js:一次云服务器请求经过了哪些层?
服务器
ikun_文6 小时前
Django框架路由Router的使用
python·pycharm·django
草莓熊Lotso7 小时前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
煎饼皮皮侠9 小时前
【设计】设计一个web版的数据库管理平台后端(之五) --借鉴mybatis
数据库·mybatis
东风破_15 小时前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
橙子家17 小时前
OSS 文件上传的几个风险点和解决方案
数据库
Julien200417 小时前
调查和解决 SELinux 问题
linux·运维·服务器·网络·学习方法