Stark组件
stark组件就是仿django admin做的一款后台管理工具
分隔为5大顺序实现
URL设计
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.db import models # Create your models here. from django.db import models 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) def __str__(self): return self.addr 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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.contrib import admin from app01.models import * # Register your models here. #注册表名------------------ admin.site.register(Book) admin.site.register(Author)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from django.contrib import admin from django.shortcuts import render,HttpResponse,redirect #匹配视图部分--------------------------------- def whq(request): return HttpResponse('whq') def add(request): return HttpResponse('增加') def delete(request): return HttpResponse('删除') def change(request): return HttpResponse('修改') def list(request): return HttpResponse('查看') #url部分---------------------------------------------- def get_urls(): temp=[] temp.append(url(r'add/', add),) temp.append(url(r'delete/', delete),) temp.append(url(r'change/', change),) temp.append(url(r'list/', list),) return temp # def get_urls2(): ''' model:admin.py里注册的表名 model_config:admin.py里注册表的配置名 :return: ''' temp=[] for model,model_config in admin.site._registry.items(): print(model,model_config) #获取APP名称----------------------- app_label = model._meta.app_label #获取表名------------------------------ mode_name = model._meta.model_name # temp.append(url(r'^%s/%s'%(app_label,mode_name),(get_urls(),None,None) )) #添加生成rul--------------------------- temp.append(url(r'^%s/%s' % (app_label, mode_name), (get_urls(), None, None))) return temp urlpatterns = [ url(r'^admin/', admin.site.urls), #输入浏览器后匹配的url-------------------- url(r'^whq/', (get_urls2(),None,None)), ] # url(r'^whq/', ([ # url(r'^test01/', test01), # url(r'^test02/', test02), # url(r'^test03/', test03), # url(r'^test04/', test04), # # ],None,None)), # ]
该功能实现了三级url基本思路 http://127.0.0.1:8092/whq/app01/book/list 查看 http://127.0.0.1:8092/whq/app01/book/add 添加 以此类推
start注册
settings文件:
注册app INSTALLED_APPS = [ 'whqstark.apps.WhqstarkConfig', ]
apps.py:
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class WhqstarkConfig(AppConfig): name = 'whqstark':app名称 def ready(self): autodiscover_modules('stark')#自动扫描stark.py文件
增删改查
查看:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from django.contrib import admin from django.shortcuts import render,HttpResponse,redirect from whqstark.service.stark import site urlpatterns = [ url(r'^admin/', admin.site.urls), #输入浏览器后匹配的url-------------------- # url(r'^whq/', (get_urls2(),None,None)), url(r'^stark/', site.urls), ]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from whqstark.service.stark import site,ModelStark from app01.models import * from django.utils.safestring import mark_safe from django.urls import reverse class BookConfig(ModelStark): def checkbox(self,obj=None,header=False): if header: return mark_safe('<input id="choice" type="checkbox">') return mark_safe('<input id="choice" type="checkbox">') def edit(self,obj=None,header=False): if header: return '操作' model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse('%s_%s_change' % (app_label, model_name), args=(obj.pk,)) print('uuuuuuuuuuuuuuuuuuuuu',obj.pk) return mark_safe('<a href="%s">编辑</a>'%_url) def deletes(self, obj=None, header=False): if header: return '操作' model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url = reverse('%s_%s_delete' % (app_label, model_name), args=(obj.pk,)) print('xxxxxxxxxxxxxxxxxxxxxxxx', obj.pk) return mark_safe('<a href="%s">删除</a>' % _url) list_display=[checkbox,'title','price','publish',edit,deletes] list_display_links=['title'] site.register(Book,BookConfig) site.register(Author)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.conf.urls import url from django.utils.safestring import mark_safe from django.shortcuts import HttpResponse,render,redirect from django.urls import reverse class ModelStark(object): list_display = ["__str__", ] # list_display_links = [] def __init__(self,model,site): self.model=model#对应的那张表 self.site=site#单例对象 # 匹配视图部分--------------------------------- def whq(self, request): return HttpResponse('whq') def add(self, request): return HttpResponse('增加') def delete(self, request, id): return HttpResponse('删除') def change(self, request, id): return HttpResponse('修改') #定制公用-------------- 删除 编辑 复选框-------------------------------------------- def checkbox(self,obj): return mark_safe('<input id="choice" type="checkbox">') def edit(self,obj=None,header=False): if header: return '操作' _url=self.get_edit_url(obj) return "<a href='%s'>编辑</a>" %obj.pk def deletes(self,obj=None,header=None): if header: return '操作' _url=self.get_delete_url(obj) return mark_safe('<a href="%s">删除</a>'%obj.pk) def new_list_display(self): temp=[] # temp.append(ModelStark.checkbox) temp.extend(self.list_display)#把数据打散,用append是把整个列表放进去 # temp.append(ModelStark.edit) # temp.append(ModelStark.deletes) print('ttttttttttttttttttttt',temp) return temp #------------------------------------------------------------- #生成增删改查4条url--------------------------------------------------- def get_add_url(self): model_name= self.model._meta.model_name app_label=self.model._meta.app_label _url=reverse('%s_%s_add'%(app_label,model_name),) return _url def get_delete_url(self,obj): model_name=self.model._meta.model_name app_label=self.model._meta.app_label _url=reverse('%s_%s_delete'%(app_label,model_name),args=(obj.pk,)) return _url def get_edit_url(self,obj): model_name = self.model._meta.model_name app_label = self.model._meta.app_label _url=reverse('%s_%s_change'%(app_label,model_name),args=(obj.pk)) return _url def get_list_url(self): model_name=self.model._meta.model_name app_label=self.model._meta.app_label _url=reverse('%s_%s_list'%(app_label,model_name)) return _url #--------------------------------------------------------------- def list(self, request): print(self.model) print(self.list_display) data_list=self.model.objects.all() #构建表头--------------------------------------- header_list=[] for field in self.new_list_display(): if callable(field): val = field(self, header=True)#header默认为Flase,为真的话就会执行函数进而返回所定义的返回值 header_list.append(val) # header_list.append() # header_list.append(field.__name__,'')#取函数名,for循环的是内存地址 else: if field=="__str__":#如果这个字段为空的话就显示数据库中显示的__str_-字段 header_list.append(self.model._meta.model_name.upper()) else: val=self.model._meta.get_field(field).verbose_name#根据list_display里的字段对象取verbose_ame header_list.append(val) new_data_list=[] for obj in data_list: temp=[]#行数据 for filed in self.list_display: if callable(filed): val=filed(self,obj) else: val= getattr(obj,filed)#字段是字符串的话,反射之后才能obj.字段进行取值 temp.append(val)#列数据 new_data_list.append(temp) print('nnnnnnnnnnnnnnnnnnnnnnnnnnnn',new_data_list) return render(request,'list_view.html',locals()) def get_urls2(self): temp = [] model_name = self.model._meta.model_name app_label = self.model._meta.app_label # url部分---------------------------------------------- temp.append(url(r'add/', self.add, name='%s_%s_add'%(app_label,model_name)), ) temp.append(url(r'(\d+)/delete/', self.delete,name='%s_%s_delete'%(app_label,model_name) ), ) temp.append(url(r'(\d+)/change/', self.change,name='%s_%s_change'%(app_label,model_name), ), ) temp.append(url(r'list/', self.list,name='%s_%s_list'%(app_label,model_name) ), ) return temp @property def geturls2(self): return (self.get_urls2(), None, None) class StarkSite(object): def __init__(self): self._registry={} def register(self,model,stark_class=None): if not stark_class: stark_class = ModelStark self._registry[model] = stark_class(model, self) # 飘黄的话是ModelStark类没有变量 def get_urls(self): temp=[] for model ,modelconfig in site._registry.items(): # 获取APP名称----------------------- app_label = model._meta.app_label # 获取表名------------------------------ mode_name = model._meta.model_name #app名字 +类名 +增/删/改/查 temp.append(url(r'%s/%s' %(app_label, mode_name),modelconfig.geturls2,)) return temp @property def urls(self): return self.get_urls(), None,None site=StarkSite()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <script src="{% static 'jquery-3.2.1.min.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script> <script src="{% static 'init_ajax.js' %}"></script> <style> .add{ margin-bottom: 10px; } </style> </head> <body> <h3>list_view页面</h3> <div class="container"> <a href="add/" class="btn btn-primary">添加</a> <div class="row "> <div class="col-md-8"> <table class="table table-bordered table-striped"> {# 生成表头#} <thead> <tr> {% for foo in header_list%} <th> {{ foo }} </th> {% endfor %} </tr> </thead> <tbody> {% for data in new_data_list %} <tr> {% for item in data %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </div> </div> </body> </html>
做完的效果:
list_display_links
def new_list_display(self): temp=[] temp.append(ModelStark.checkbox) temp.extend(self.list_display)#把数据打散,用append是把整个列表放进去 #---------------------有list_display_links则不显示编辑字段 if not self.list_display_links: temp.append(ModelStark.edit) print('sssssssssssssssssssssssssssss',self.list_display_links) temp.append(ModelStark.deletes) return temp
class BookConfig(ModelStark): list_display=['title','price','publish'] list_display_links=['title'] # print('lllllllllllllllllllllllllll',list_display) site.register(Book,BookConfig)
封装查看页面(list):
封装后
class show_list:
def __init__(self,config,data_list):
self.config=config
self.data_list=data_list
# 构建表头---------------------------------------
def get_header(self):
header_list = []
for field in self.config.new_list_display():
if callable(field):
val = field(self.config, header=True) # header默认为Flase,为真的话就会执行函数进而返回所定义的返回值
header_list.append(val)
# header_list.append()
# header_list.append(field.__name__,'')#取函数名,for循环的是内存地址
else:
if field == "__str__": # 如果这个字段为空的话就显示数据库中显示的__str_-字段
header_list.append(self.config.model._meta.model_name.upper())
else:
val = self.config.model._meta.get_field(field).verbose_name # 根据list_display里的字段对象取verbose_ame
header_list.append(val)
return header_list
# print('headerhhhhhhhhhhhhhhhhhhh', header_list)
def get_body(self):
# 构建表单数据----------------------------------------
new_data_list = []
for obj in self.data_list:
temp = [] # 行数据
for filed in self.config.new_list_display():
if callable(filed):
val = filed(self.config, obj)
else:
val = getattr(obj, filed) # 字段是字符串的话,反射之后才能obj.字段进行取值
temp.append(val) # 列数据
new_data_list.append(temp)
return new_data_list
调用
def list(self, request):
print(self.model)
print(self.list_display)
data_list=self.model.objects.all()
showlist=show_list(self,data_list)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<thead> <tr> {% for foo in showlist.get_header%} <th> {{ foo }} </th> {% endfor %} </tr> </thead> <tbody> {% for data in showlist.get_body %} <tr> {% for item in data %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %}
分页-search-actions
filter过滤
POP功能
def new_list_display(self):
temp=[]
temp.append(ModelStark.checkbox)
temp.extend(self.list_display)#把数据打散,用append是把整个列表放进去
#---------------------有list_display_links则不显示编辑字段
if not self.list_display_links:
temp.append(ModelStark.edit)
print('sssssssssssssssssssssssssssss',self.list_display_links)
temp.append(ModelStark.deletes)
print('ttttttttttttttttttttt',temp)
return temp
撸起袖子加油干!!!