当前位置:   article > 正文

Django Admin 后台自定制技巧_django admin定制

django admin定制

Django Admin是Django框架内置的一个强大的后台管理系统,用于管理应用程序的数据模型和进行常见的管理任务。Django Admin提供了一个基于Web的用户界面,使开发者可以轻松地执行各种管理操作,而无需编写大量的自定义代码。

Django Admin 简单配置

settings.py

  1. LANGUAGE_CODE = 'zh-hans'
  2. TIME_ZONE = 'Asia/Shanghai'

models.py

  1. from django.db import models
  2. import sqlite3
  3. from django.utils.html import format_html
  4. STATUS_CHOICES = (('d', '正常'),('p', '警告'),('w', '损坏'),)
  5. class HostDB(models.Model):
  6. id = models.AutoField(primary_key=True)
  7. hostname = models.CharField(max_length=64,verbose_name="主机名称")
  8. hostaddr = models.TextField(max_length=64,verbose_name="主机地址")
  9. hostCPU = models.CharField(max_length=64,verbose_name="主机CPU")
  10. hostMEM = models.CharField(max_length=64,verbose_name="主机内存")
  11. DataTime = models.DateTimeField(verbose_name="主机当前时间")
  12. hostUser = models.CharField(max_length=64,verbose_name="负责人")
  13. hostStats = models.CharField(max_length=1,choices=STATUS_CHOICES,verbose_name="状态")
  14. def __str__(self):
  15. return self.hostname
  16. # 自定义方法,主要负责给主机标注颜色
  17. def Status(self):
  18. if self.hostStats == 'd':
  19. format_td = format_html('<span style="padding:2px;background-color:green;color:white">正常</span>')
  20. elif self.hostStats == 'p':
  21. format_td = format_html('<span style="padding:2px;background-color:yellow;color:black">警告</span>')
  22. elif self.hostStats == 'w':
  23. format_td = format_html('<span style="padding:2px;background-color:red;color:white">损坏</span>')
  24. return format_td
  25. Status.short_description = "当前状态"

admin.py

  1. from django.contrib import admin
  2. from MyWeb.models import *
  3. # 必须继承ModelAdmin基类,才可以调整参数,HostDB则是你的表的名称
  4. @admin.register(HostDB)
  5. class MyAdmin(admin.ModelAdmin):
  6. admin.site.site_title="自动化后台管理"
  7. admin.site.site_header = "Django 自动化运维"
  8. # list_display = 你需要展示的字段应该写在这里,此处是数据库中的字段
  9. list_display = ("hostname","hostaddr","hostCPU","hostMEM","DataTime","hostUser","Status")
  10. # search_fields = 用于添加一个搜索框,此处以hostaddr作为查询条件
  11. search_fields = ("hostaddr",)
  12. # list_filter = 设置一个过滤器,此处是以hostname作为过滤条件
  13. list_filter = ("hostname",)
  14. # ordering = 设置一个排序条件,此处是以id作为排序依据
  15. ordering = ("id",)
  16. #list_per_page = 设置每页显示多少条记录,默认是100条
  17. list_per_page = 10
  18. #list_editable = 设置默认可编辑字段
  19. #list_editable = ("DataTime",)
  20. # date_hierarchy = 显示详细时间分层筛选
  21. date_hierarchy = 'DataTime'
  22. # readonly_fields = 可以设置只读字段,就是无法修改的字段
  23. readonly_fields = ("hostCPU","hostMEM",)
  24. python manage.py makemigrations
  25. python manage.py migrate
  26. python manage.py createsuperuser

效果如下。

另外找到一个不错的主题

  1. pip install simpleui
  2. vim settings.py
  3. INSTALLED_APPS = [
  4. 'simpleui',
  5. 'django.contrib.admin',
  6. 'myweb.apps.MywebConfig',
  7. ]
  8. STATIC_URL = '/static/'
  9. STATICFILES_DIRS = [
  10. os.path.join(BASE_DIR, "static"),
  11. ]

定制主机管理菜单

  1. vim settings.py
  2. LANGUAGE_CODE = 'zh-hans'
  3. TIME_ZONE = 'Asia/Shanghai'
  4. apps.py
  5. from django.apps import AppConfig
  6. class MywebConfig(AppConfig):
  7. name = 'MyWeb'
  8. verbose_name = "服务器集群"

models.py

  1. from django.db import models
  2. from django.utils.html import format_html
  3. STATUS_CHOICES = (('d', '正常'),('p', '警告'),('w', '损坏'),)
  4. class HostInfo(models.Model):
  5. id = models.AutoField(primary_key=True)
  6. HostName = models.CharField(max_length=64,verbose_name="主机名")
  7. HostAddr = models.CharField(max_length=64,verbose_name="主机IP")
  8. HostModel = models.CharField(max_length=64,verbose_name="设备型号")
  9. HostCPU = models.CharField(max_length=64,verbose_name="主机CPU")
  10. HostMem = models.CharField(max_length=64,verbose_name="主机内存")
  11. HostDisk = models.CharField(max_length=64,verbose_name="主机磁盘")
  12. HostSys = models.CharField(max_length=64,verbose_name="操作系统")
  13. HostZone = models.CharField(max_length=64,verbose_name="区域")
  14. DataTime = models.DateField(max_length=64,verbose_name="统计时间")
  15. HostPeple = models.CharField(max_length=64, verbose_name="负责人")
  16. HostStats = models.CharField(max_length=1,choices=STATUS_CHOICES,verbose_name="状态")
  17. def __str__(self):
  18. return self.HostName
  19. # 用于给本表指定一个别名
  20. class Meta():
  21. verbose_name = "Web前台集群"
  22. verbose_name_plural= "Web前台集群"
  23. # 自定义方法,主要负责给主机标注颜色
  24. def Status(self):
  25. if self.HostStats == 'd':
  26. format_td = format_html('<span style="padding:2px;background-color:green;color:white">正常</span>')
  27. elif self.HostStats == 'p':
  28. format_td = format_html('<span style="padding:2px;background-color:yellow;color:black">警告</span>')
  29. elif self.HostStats == 'w':
  30. format_td = format_html('<span style="padding:2px;background-color:red;color:white">损坏</span>')
  31. return format_td
  32. Status.short_description = "状态"

admin.py

  1. from django.contrib import admin
  2. from MyWeb.models import *
  3. # 必须继承ModelAdmin基类,才可以调整参数,HostDB则是你的表的名称
  4. @admin.register(HostInfo)
  5. class MyAdmin(admin.ModelAdmin):
  6. admin.site.site_title="自动化后台管理"
  7. admin.site.site_header = "Django 自动化运维"
  8. # list_display = 你需要或者想要展示在页面中的字段
  9. list_display = ("HostName","HostAddr","HostModel","HostCPU","HostMem","HostDisk","HostSys","HostZone","DataTime","HostPeple","Status")
  10. # search_fields = 添加搜索功能,并以HostName作为搜索条件
  11. search_fields = ("HostName",)
  12. # ordering = 设置以HostAddr作为排序条件
  13. ordering = ("HostAddr",)
  14. # list_per_page = 设置每页显示的字段数
  15. list_per_page = 10

自定义页面功能

在templates中新建一个名称为lyshark.html的文件

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% load static %}
  4. {% block title %}{{ site_title|default:_('Django site admin') }}{% endblock %}
  5. {% block content %}
  6.  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  7. <script>
  8. $(".breadcrumbs").append("&nbsp;&nbsp;<a href=\"/admin/\">仪表盘</a>");
  9. $(".breadcrumbs").append("&nbsp;&nbsp;<a href=\"/admin/\">主机监控</a>");
  10. $(".breadcrumbs").append("&nbsp;&nbsp;<a href=\"/admin/\">命令执行</a>");
  11. $(".breadcrumbs").append("&nbsp;&nbsp;<a href=\"/admin/\">图表绘制</a>");
  12. $(".breadcrumbs").append("&nbsp;&nbsp;<a href=\"/admin/\">批量CMD</a>");
  13. </script>
  14. <form action="/lyshark/" method="post">
  15. 用户:<input type="text" value="text">
  16. 密码:<input type="text" value="text">
  17. <input type="text" value="text">
  18. <input type="text" value="text">
  19. <input type="submit" value="提交表单">
  20. </form>
  21. {% endblock %}

接着在view.py中增加一条视图函数

  1. from django.shortcuts import render
  2. from django.contrib.auth.decorators import login_required
  3. @login_required(login_url="/admin/login")
  4. def lyshark(request):
  5. return render(request,"lyshark.html")

最后别忘了在urls.py里面添加映射记录.

  1. from MyWeb import views
  2. urlpatterns = [
  3. path('admin/', admin.site.urls),
  4. path("lyshark/",views.lyshark)
  5. ]

上方添加了装饰器,函数,只有用户登陆后才可以访问到定制页面,如果没有登陆则提示需要登陆,这样更加灵活了。

添加各种标志

添加已过期标志: 判断当前时间是否与数据库时间一致,并显示过期状态.

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. @admin.register(HostDB)
  5. class MyAdmin(admin.ModelAdmin):
  6. list_display = ("id","date","Status")
  7. # name: models.py
  8. from django.db import models
  9. from django.utils.html import format_html
  10. import datetime
  11. class HostDB(models.Model):
  12. id = models.AutoField(primary_key=True)
  13. date = models.CharField(max_length=64)
  14. def Status(self):
  15. NowData = datetime.date.today()
  16. if self.date >= str(NowData):
  17. ret = "未过期"
  18. color = "green"
  19. return format_html('<span style="color:{};">{}</span>',color,ret,)
  20. else:
  21. ret = "已过期"
  22. color = "red"
  23. return format_html('<span style="color:{};">{}</span>', color, ret,)
  24. Status.short_description = "是否过期"

添加进度条展示 琢磨了一下,把进度条也堆上了。呵呵

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. @admin.register(HostDB)
  5. class MyAdmin(admin.ModelAdmin):
  6. list_display = ("id","Count","Speed")
  7. # name: models.py
  8. from django.db import models
  9. from django.utils.html import format_html
  10. class HostDB(models.Model):
  11. id = models.AutoField(primary_key=True)
  12. Count = models.IntegerField()
  13. def Speed(self):
  14. return format_html('<progress max="100" value="{}"></progress>',self.Count)
  15. Speed.short_description = "当前进度"

实现查看标签 添加一个查看标签

  1. def Check(self):
  2. return format_html('<a href="/admin/MyWeb/hostdb/{}/change/">查看</a>',self.id)

增加自定义actions: 自定义Action标签,Action标签就是Admin页面中左上角的横线部分,我们自己增加新的.

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. # 必须继承ModelAdmin基类,才可以调整参数,HostDB则是你的表的名称
  5. @admin.register(HostInfo)
  6. class MyAdmin(admin.ModelAdmin):
  7. admin.site.site_title="自动化后台管理"
  8. admin.site.site_header = "Django 管理平台"
  9. <省略部分...>
  10. def func(self,request,queryset):
  11. # 此处可以写一些执行动作
  12. print(self,request,queryset)
  13. func.short_description = "自定义active动作"
  14. actions = [func,]
  15. # Action选项都是在页面上方显示
  16. actions_on_top = True
  17. # Action选项都是在页面下方显示
  18. actions_on_bottom = False
  19. # 是否显示选择个数
  20. actions_selection_counter = True

添加防火墙管理模块

  1. {% extends "admin/base_site.html" %}
  2. {% load i18n static %}
  3. {% block content %}
  4. <link rel="stylesheet" href="https://cdn.lyshark.com/cdn/bootstrap3.css" />
  5. <script src="https://cdn.lyshark.com/cdn/jquery.js"></script>
  6. <style>
  7. #content {
  8. padding: 10px 10px;
  9. }
  10. .panel-body {
  11. padding: 10px;
  12. }
  13. </style>
  14. <div class="panel panel-default">
  15. <div class="panel-heading">
  16. <h3 class="panel-title">防火墙配置模块</h3>
  17. </div>
  18. <div class="panel-body">
  19. <div class="panel panel-default">
  20. <div class="panel-body">
  21. <div class="firewall-port-box">
  22. <input type="text" class="bt-input-text mr5" style="width: 200px;" id="SourceAddr" placeholder="源地址">
  23. <input type="text" class="bt-input-text mr5" id="Remarks" placeholder="备注/说明">
  24. <select id="firewalldType" class="bt-input-text c5 mr5" name="type" style="width:80px;">
  25. <option value="accept">放行IP</option>
  26. <option value="drop">屏蔽IP</option>
  27. </select>
  28. <button id="toAccept" class="btn btn-default btn-sm" type="button">提交更改</button>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="panel panel-default">
  33. <div class="panel-body">
  34. <table class="table table-hover">
  35. <thead>
  36. <tr>
  37. <th>编号</th>
  38. <th>IP地址</th>
  39. <th>动作</th>
  40. <th>添加时间</th>
  41. <th>备注</th>
  42. <th>操作</th>
  43. </tr>
  44. </thead>
  45. <tbody>
  46. {% for item in data %}
  47. <tr>
  48. <td> {{ item.id }}</td>
  49. <td> {{ item.SourceAddr }}</td>
  50. <td> {{ item.Action }}</td>
  51. <td> {{ item.DataTime }}</td>
  52. <td> {{ item.Remarks }}</td>
  53. <td><a href="index.html">删除</a></td>
  54. </tr>
  55. {% endfor %}
  56. </tbody>
  57. </table>
  58. </div>
  59. </div>
  60. </div>
  61. </div>
  62. <script>
  63. $(document).ready(function(){
  64. $("#toAccept").click(function(){
  65. var message = {"type":null,"SourceAddr":null,"Remarks":null};
  66. message['type'] = $("#firewalldType option:selected").val();
  67. message['SourceAddr'] = $("#SourceAddr").val();
  68. message['Remarks'] = $("#Remarks").val();
  69. data = JSON.stringify(message);
  70. $.ajax({
  71. url:"/echo/",
  72. type:"POST",
  73. dataType:"json",
  74. data:data,
  75. success:function () {
  76. window.location.reload();
  77. }
  78. });
  79. });
  80. });
  81. </script>
  82. {% endblock %}
  1. from django.shortcuts import render,HttpResponse
  2. from MyWeb import models
  3. import paramiko,time,json
  4. ssh = paramiko.SSHClient()
  5. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  6. def ssh_shell(address,username,password,port,command):
  7. try:
  8. ssh.connect(address,port=port,username=username,password=password,timeout=1)
  9. stdin, stdout, stderr = ssh.exec_command(command)
  10. result = stdout.read()
  11. if not result:
  12. result=stderr.read()
  13. ssh.close()
  14. return result.decode()
  15. except Exception:
  16. return 0
  17. def echo(request):
  18. if request.method == "GET":
  19. obj = models.FireWallDB.objects.all()
  20. print(obj)
  21. return render(request,"index.html",{"data":obj})
  22. else:
  23. recv = json.loads(request.body.decode("utf-8"))
  24. addr = recv.get("SourceAddr")
  25. remak = recv.get("Remarks")
  26. if recv.get("type") == "accept":
  27. cmd = 'firewall-cmd --add-rich-rule \'rule family=ipv4 source address="{}" accept\''.format(addr)
  28. count = models.FireWallDB.objects.filter(SourceAddr=addr).count()
  29. if count <2:
  30. retn = ssh_shell("192.168.1.20","root","123","22",cmd)
  31. if retn !=0:
  32. obj = models.FireWallDB()
  33. obj.SourceAddr = addr
  34. obj.Action = "放行"
  35. obj.DataTime = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
  36. obj.Remarks = remak
  37. obj.SourceCMD = cmd
  38. obj.save()
  39. print("ok")
  40. elif recv.get("type") == "drop":
  41. cmd = 'firewall-cmd --add-rich-rule \'rule family=ipv4 source address="{}" drop\''.format(addr)
  42. print(cmd)
  43. else:
  44. print("最多两个")
  45. return HttpResponse("ok")
  46. return render(request,"index.html")
  1. from django.db import models
  2. class FireWallDB(models.Model):
  3. id = models.AutoField(primary_key=True)
  4. SourceAddr = models.CharField(max_length=64)
  5. Action = models.CharField(max_length=64)
  6. DataTime = models.CharField(max_length=64)
  7. Remarks = models.CharField(max_length=64)
  8. SourceCMD = models.CharField(max_length=512)

简单的Admin定制: 简单的过滤器使用技巧.

  1. # name: settings.py
  2. LANGUAGE_CODE = 'zh-hans'
  3. TIME_ZONE = 'Asia/Shanghai'
  4. # name: apps.py
  5. from django.apps import AppConfig
  6. class MywebConfig(AppConfig):
  7. name = 'MyWeb'
  8. verbose_name = "服务器集群"
  9. # name: 最后别忘了建库建表
  10. python manage.py makemigrations
  11. python manage.py migrate
  12. python manage.py createsuperuser
  1. # name: models.py
  2. from django.db import models
  3. from django.utils.html import format_html
  4. STATUS_CHOICES = (('d', '正常'),('p', '警告'),('w', '损坏'),)
  5. class HostInfo(models.Model):
  6. id = models.AutoField(primary_key=True)
  7. HostName = models.CharField(max_length=64,verbose_name="主机名")
  8. HostAddr = models.CharField(max_length=64,verbose_name="主机IP")
  9. DataTime = models.DateField(max_length=64,verbose_name="统计时间")
  10. HostStats = models.CharField(max_length=1,choices=STATUS_CHOICES,verbose_name="状态")
  11. def __str__(self):
  12. return self.HostName
  13. # 用于给本表指定别名,这样前端就不是英文的了
  14. class Meta():
  15. verbose_name = "Web前台集群"
  16. verbose_name_plural= "Web前台集群"
  17. # 自定义方法,主要负责给主机标注颜色
  18. def Status(self):
  19. if self.HostStats == 'd':
  20. format_td = format_html('<span style="padding:2px;background-color:green;color:white">正常</span>')
  21. elif self.HostStats == 'p':
  22. format_td = format_html('<span style="padding:2px;background-color:yellow;color:black">警告</span>')
  23. elif self.HostStats == 'w':
  24. format_td = format_html('<span style="padding:2px;background-color:red;color:white">损坏</span>')
  25. return format_td
  26. Status.short_description = "状态"
  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. # 必须继承ModelAdmin基类,才可以调整参数,HostDB则是你的表的名称
  5. @admin.register(HostInfo)
  6. class MyAdmin(admin.ModelAdmin):
  7. admin.site.site_title="自动化后台管理"
  8. admin.site.site_header = "Django 管理平台"
  9. # list_display = 你需要或者想要展示在页面中的字段
  10. list_display = ("HostName","HostAddr","DataTime","Status")
  11. # search_fields = 添加搜索功能,并以HostName,HostAddr作为搜索条件
  12. search_fields = ("HostName","HostAddr",)
  13. # ordering = 设置以id号作为排序条件
  14. ordering = ("id",)
  15. # list_per_page = 设置每页显示数据条数
  16. list_per_page = 10
  17. # list_filter = 设置一个过滤器,此处是以hostname作为过滤条件
  18. list_filter = ("HostName",)
  19. #list_editable = 设置默认可编辑字段
  20. list_editable = ("DataTime",)
  21. # date_hierarchy = 显示详细时间分层筛选
  22. date_hierarchy = 'DataTime'
  23. # readonly_fields = 可以设置只读字段,就是无法修改的字段
  24. readonly_fields = ("HostAddr",)
  25. # list_display_links 指定点击HostAddr进入编辑状态
  26. list_display_links = ("HostAddr",)

添加已过期标志: 通过取出当前时间与数据库中现有时间对比,来实现是否过期.

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. @admin.register(HostDB)
  5. class MyAdmin(admin.ModelAdmin):
  6. list_display = ("id","date","Status")
  7. # name: models.py
  8. from django.db import models
  9. from django.utils.html import format_html
  10. import datetime
  11. class HostDB(models.Model):
  12. id = models.AutoField(primary_key=True)
  13. date = models.CharField(max_length=64)
  14. def Status(self):
  15. NowData = datetime.date.today()
  16. if self.date >= str(NowData):
  17. ret = "未过期"
  18. color = "green"
  19. return format_html('<span style="color:{};">{}</span>',color,ret,)
  20. else:
  21. ret = "已过期"
  22. color = "red"
  23. return format_html('<span style="color:{};">{}</span>', color, ret,)
  24. Status.short_description = "是否过期"

添加进度条展示: HTML5默认支持进度条标签,使用progress我们直接使用这个标签就好了.

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. @admin.register(HostDB)
  5. class MyAdmin(admin.ModelAdmin):
  6. list_display = ("id","Count","Speed")
  7. # name: models.py
  8. from django.db import models
  9. from django.utils.html import format_html
  10. class HostDB(models.Model):
  11. id = models.AutoField(primary_key=True)
  12. Count = models.IntegerField()
  13. def Speed(self):
  14. return format_html('<progress max="100" value="{}"></progress>',self.Count)
  15. Speed.short_description = "当前进度"

增加自定义actions: 自定义Action标签,Action标签就是Admin页面中左上角的横线部分,我们自己增加新的.

  1. # name: admin.py
  2. from django.contrib import admin
  3. from MyWeb.models import *
  4. # 必须继承ModelAdmin基类,才可以调整参数,HostDB则是你的表的名称
  5. @admin.register(HostInfo)
  6. class MyAdmin(admin.ModelAdmin):
  7. admin.site.site_title="自动化后台管理"
  8. admin.site.site_header = "Django 管理平台"
  9. <省略部分...>
  10. def func(self,request,queryset):
  11. # 此处可以写一些执行动作
  12. print(self,request,queryset)
  13. func.short_description = "自定义active动作"
  14. actions = [func,]
  15. # Action选项都是在页面上方显示
  16. actions_on_top = True
  17. # Action选项都是在页面下方显示
  18. actions_on_bottom = False
  19. # 是否显示选择个数
  20. actions_selection_counter = True
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/521447
推荐阅读
相关标签
  

闽ICP备14008679号