看完前一篇,相信你对Django中admin组件有了一定的了解,下面就一起来设计一个自己的admin组件,Xadmin
Xadmin初始化
首先,在一个django项目中新建两个app,一个用于测试Xadmin(testXadmin),一个书写Xadmin组件(Xadmin),然后将两个app都注册到setting文件中:
然后在template文件夹中设置四个网页页面:
add_view.html
change_view.html
delete_view.html
list_view.html
以一个页面为例,做一个简单的示范:add_view.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>查看</h3> </body> </html>
步骤一 书写注册语句
注册语句为:
在Xadmin.apps.py中添加如下代码:
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class XadminConfig(AppConfig): name = 'Xadmin' def ready(self): # 加载类的时候会自动加载 autodiscover_modules("Xadmin")
步骤二 书写site单例对象,渲染基类对象
在一个利于导入的地方写下生成site的url生成对象,和渲染基类对象,例如我在Xadmin APP下新建一个server文件夹,server中新建Xadmin.py文件
Xadmin.py:
from django.conf.urls import url from django.shortcuts import HttpResponse, render, redirect class ModelXadmin(object): def __init__(self, model, site): self.model = model self.site = site def list_view(self, request): print("self.model", self.model) data_list = self.model.objects.all() print("data_list", data_list) return render(request, 'list_view.html', {"data_list": data_list}) def add_view(self, request): return render(request, 'add_view.html') def change_view(self, request, id): return render(request, 'change_view.html') def delete_view(self, request, id): return render(request, 'delete_view.html') def get_urls2(self): temp = [] temp.append(url(r"^$", self.list_view)) temp.append(url(r"^add/$", self.add_view)) temp.append(url(r"^(d+)/change/$", self.change_view)) temp.append(url(r"^(d+)/delete/$", self.delete_view)) return temp @property def urls2(self): return self.get_urls2(), None, None class XadminSite(object): """ url分配,生成对象 """ def __init__(self, name='admin'): self._registry = {} def get_urls(self): print(self._registry) # {Book:modelAdmin(Book),.......} temp = [] for model, admin_class_obj in self._registry.items(): app_name = model._meta.app_label model_name = model._meta.model_name temp.append(url(r'^{0}/{1}/'.format(app_name, model_name), admin_class_obj.urls2), ) ''' url(r"app01/book",ModelXadmin(Book,site).urls2) url(r"app01/publish",ModelXadmin(Publish,site).urls2) url(r"app02/order",ModelXadmin(Order,site).urls2) ''' return temp @property def urls(self): return self.get_urls(), None, None # 返回的是一个元组,元组第一个参数是列表 def register(self, model, admin_class=None, **options): if not admin_class: admin_class = ModelXadmin self._registry[model] = admin_class(model, self) # {Book:ModelAdmin(Book),Publish:ModelAdmin(Publish)} site = XadminSite()
这里生成的site对象就是url中用的site对象
改写url.py文件
将原来admin对应的路径处理函数换成自己Xadmin组件中的site.urls
在测试app中进行测试:
在testXadmin下的models.py文件中书写表关系对应的类:
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() # 与AuthorDetail建立一对一的关系 authorDetail = models.OneToOneField(to="AuthorDetail", on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday = models.DateField() telephone = models.BigIntegerField() addr = models.CharField(max_length=64) class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) publishDate = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2) # 与Publish建立一对多的关系,外键字段建立在多的一方 publish = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors = models.ManyToManyField(to='Author', ) def __str__(self): return self.title
在testXadmin下新建Xadmin.py文件,文件内容如下:
from Xadmin.service.Xadmin import site, ModelXadmin from testXadmin.models import * # Register your models here. class BookConfig(ModelXadmin): list_display = ["title", "prcie"] class PublishConfig(ModelXadmin): list_display = ["name"] site.register(Book, BookConfig) site.register(Publish, PublishConfig) site.register(Author) site.register(AuthorDetail)
这样就完成了使用Xadmin组件提换了原来的admin组件,而且在测试app中还进行了测试,下面看测试结果
验证成功,后面编写前端页面即可替代原admin组件