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


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

    1、创建空模型:

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

    2、注册到admin.py

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

    1. from django.contrib import admin
    2. from django.shortcuts import render
    3. from apps.setting.models import ResetSVNAuthFileModel
    4. @admin.register(ResetSVNAuthFileModel)
    5. class FeedbackStatsAdmin(admin.ModelAdmin):
    6. def changelist_view(self, request, extra_content=None):
    7. template_name = 'reset_svn_auth_file.html'
    8. return render(request, template_name)
    reset_svn_auth_file.html:
    1. {% extends "admin/base_site.html" %}
    2. {% load static %}
    3. {% block content %}
    4. <div class="text-center">
    5. <button onclick="resetFunction()" id="resetButton" class="btn btn-primary btn-lg">重置授权文件button>
    6. div>
    7. {% endblock %}
    8. {% block extrahead %}
    9. <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11">script>
    10. <script>
    11. function resetFunction() {
    12. // 禁用按钮
    13. document.getElementById("resetButton").disabled = true;
    14. // 发送 AJAX 请求到 Django 视图
    15. fetch('/admin-api/reset-auth-file').then(response => {
    16. if (response.ok) {
    17. Swal.fire({
    18. icon: 'success',
    19. title: 'OK',
    20. text: '操作成功',
    21. })
    22. } else {
    23. response.json().then(data => {
    24. console.log(data)
    25. Swal.fire({
    26. icon: 'error',
    27. title: '重置失败',
    28. text: data.msg,
    29. })
    30. })
    31. }
    32. }).catch((error) => {
    33. Swal.fire({
    34. icon: 'error',
    35. title: 'Oops...',
    36. text: '请求失败',
    37. })
    38. }).finally(() => {
    39. // 恢复按钮状态
    40. document.getElementById("resetButton").disabled = false;
    41. });
    42. }
    43. script>
    44. {% endblock %}

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

    3、定义后端路由和接口

    django总路由:

    1. from django.contrib import admin
    2. from django.urls import path, include
    3. from apps.repository.views import ResetAuthFileView
    4. admin_api = [
    5. path('reset-auth-file/', ResetAuthFileView.as_view(), name='reset-auth-file'),
    6. ]
    7. urlpatterns = [
    8. path('admin/', admin.site.urls),
    9. path('admin-api/', include(admin_api)), # 在admin 自定义页面中发送过来的请求
    10. ]

    接口函数:

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

    大功告成,看成果:

    点击菜单后的页面:

  • 相关阅读:
    [论文总结] 深度学习在农业领域应用论文笔记10
    文件上传四次绕过
    插座为啥左零右火,可不可以反接,会有什么后果?80%电工答不出
    H5 微信扫一扫
    MySQL第一弹
    Web前端入门(十六)CSS三大特性
    Web前端:JavaScript-->流程控制语句*笔记
    【EMQX 5.0】2.2.4 Authentication 认证
    [工业自动化-7]:西门子S7-15xxx编程 - PLC主站 - 电源模块
    张俊将出席用磁悬浮技术改变生活演讲
  • 原文地址:https://blog.csdn.net/bocai_xiaodaidai/article/details/138004953