1、编辑按钮构建完成
1、必备知识预习
2、mark_safe模块:将html标签安全传输
3、构造表单数据
4、反向解析
https://www.cnblogs.com/yuanchenqi/articles/7629939.html
5、编辑按钮构造
# -*- coding: utf-8 -*- # @Time : 2018/08/17 0017 14:52 # @Author : Venicid from stark.service import stark from .models import * from django.utils.safestring import mark_safe from django.urls import reverse class AuthorConfig(stark.ModelStark): def edit(self,obj): # return mark_safe("<a>编辑</a>") # 方案1:固定url # return mark_safe("<a href=/stark/app01/userinfo/%s/change>编辑</a>") # 方案2:拼接url # return mark_safe("<a href='%s/change'>编辑</a>") # 方案3:反向解析 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("_url",_url) return mark_safe("<a href='%s'>编辑</a>"%_url) list_display = ['pk', 'name', 'age', edit] stark.site.register(Book) stark.site.register(Publish) stark.site.register(Author,AuthorConfig) stark.site.register(AuthorDetail) print(stark.site._registry) """ {<class 'app01.models.Book'>: <stark.service.stark.ModelStark object at 0x0000003AA7439630>, <class 'app01.models.Publish'>: <stark.service.stark.ModelStark object at 0x0000003AA7439668>, <class 'app01.models.Author'>: <stark.service.stark.ModelStark object at 0x0000003AA74396A0>, <class 'app01.models.AuthorDetail'>: <stark.service.stark.ModelStark object at 0x0000003AA7439940>} """
# -*- coding: utf-8 -*- # @Time : 2018/08/17 0017 14:46 # @Author : Venicid from django.conf.urls import url from django.shortcuts import HttpResponse,render class ModelStark(object): list_display = ["__str__"] # 子类中没有,直接用父类自己的 def __init__(self,model, site): self.model = model self.site = site def list_view(self, request): print(self.model) # <class 'app01.models.Book'> 用户访问的模型表 print('list_display',self.list_display) # 获取data_list data_list = self.model.objects.all() # [obj1,obj2,...] new_data_list = [] for obj in data_list: # Book表模型,Author表模型 temp = [] for filed in self.list_display: # ['name','age'] if callable(filed): # edit() 可调用的 val = filed(self,obj) # 直接调用edit()函数 else: val = getattr(obj,filed) # 反射 obj是实例对象,name是方法 temp.append(val) new_data_list.append(temp) print('new_data_list',new_data_list) # 构造数据 [['jack', 44], ['mark', 33]] return render(request,'list_view.html', locals()) def add(self, request): return HttpResponse('add') def delete(self, request, id): return HttpResponse('delete') def change(self, request, id): return HttpResponse('change') def get_urls2(self): """构造 add/delete/change""" model_name = self.model._meta.model_name app_label = self.model._meta.app_label temp = [] temp.append(url(r'^$', self.list_view, name='%s_%s_list'%(app_label,model_name))) 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))) return temp @property def urls2(self): return self.get_urls2(), None, None class StarkSite(object): """site单例类""" 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) def get_urls(self): """构造一层urls app01/book""" temp = [] for model, stark_class_obj in self._registry.items(): print(model, 'stark_clas_obj', stark_class_obj) # 不同的model模型表 """ <class 'app01.models.UserInfo'> ----> <app01.starkadmin.UserConfig object at 0x00000072DDB65198> <class 'app01.models.Book'> ----> <stark.service.stark.ModelStark object at 0x00000072DDB65240> """ app_label = model._meta.app_label # app01 model_name = model._meta.model_name # book # temp.append(url(r'^%s/%s'%(app_label, model_name),([],None,None))) temp.append(url(r'^%s/%s/'%(app_label, model_name),stark_class_obj.urls2)) """ path('app01/userinfo/',UserConfig(Userinfo,site).urls2), path('app01/book/',ModelStark(Book,site).urls2), """ return temp @property def urls(self): # return [],None,None return self.get_urls(),None,None site = StarkSite() # 单例对象
2、构造表头,删除,checkbox,links编辑
1、必备小知识
2、list_display显示表头
3、verbose_name显示中文
4、list_display_links编辑link构造
3、代码+总结
1、总结
完成
(list_display)
(list_display_links)
1.根据str,拿字段对象,取中文
val = self.model._meta.get_field(field).verbose_name
2.模型名称,app名称
model_name = self.model._meta.model_name
app_lable = self.model._meta.app_label
3.判断是否可调用
if callable(field):
val = field(self, header = True)
4.字符串找对象得属性,反射
val = getattr(data, field)
5.返回标签
return mark_safe("<input id='choice' type='checkbox'>")
6.插入数组[]
temp.append(ModelStark.checkbox)
temp.extend(self.list_display)
7.反向解析,含正则
_url = reverse("%s_%s_delete" % (app_label, model_name), args=(obj.pk,))
_url = reverse("%s_%s_add" % (app_label, model_name))
8.复选框,全选/全不选
$('#choice').click(function () {
if($(this).prop('checked')){
$('.choice_item').prop('checked',true)
}else{
$('.choice_item').prop('checked',false)
}
})
2、starkadmin.py
from stark.service import stark from .models import * class AuthorConfig(stark.ModelStark): list_display = ['nid', 'name', 'age'] list_display_links = ['name','age'] stark.site.register(Book) stark.site.register(Publish) stark.site.register(Author,AuthorConfig) stark.site.register(AuthorDetail) print(stark.site._registry)
3、stark/server/stark.py
# -*- coding: utf-8 -*- # @Time : 2018/08/17 0017 14:46 # @Author : Venicid from django.conf.urls import url from django.shortcuts import HttpResponse,render from django.utils.safestring import mark_safe 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 checkbox(self,obj=None, header=False): if header: return mark_safe("<input id='choice' type='checkbox'>") return mark_safe("<input class='choice_item' type='checkbox'>") def edit(self,obj=None, header=False): if header: return "操作" # 方案1:固定url # return mark_safe("<a href=/stark/app01/userinfo/%s/change>编辑</a>") # 方案2:拼接url # return mark_safe("<a href='%s/change'>编辑</a>") # 方案3:反向解析 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("_url",_url) 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,)) return mark_safe("<a href='%s'>删除</a>"%_url) def new_list_play(self): """构建 ['checkbox','pk', 'name', 'age', edit,'delete']""" temp = [] temp.append(ModelStark.checkbox) temp.extend(self.list_display) if not self.list_display_links: temp.append(ModelStark.edit) temp.append(ModelStark.deletes) return temp def list_view(self, request): print(self.model) # <class 'app01.models.Book'> 用户访问的模型表 # 构建表头 header_list = [] # # header_list = ['选择','pk',...'操作','操作'] for field in self.new_list_play(): if callable(field): # header_list.append(field.__name__) val = field(self,header=True) header_list.append(val) else: if field == "__str__": header_list.append(self.model._meta.model_name.upper()) else: val = self.model._meta.get_field(field).verbose_name # 中文名称 header_list.append(val) # 构建表单 data_list = self.model.objects.all() # [obj1,obj2,...] new_data_list = [] for obj in data_list: # Book表模型,Author表模型 temp = [] for field in self.new_list_play(): # ['name','age'] if callable(field): # edit() 可调用的 val = field(self,obj) # 直接调用edit()函数 print('val--------->',val) else: val = getattr(obj,field) # 反射 obj是实例对象,name是方法 # list_display_links 按钮 if field in self.list_display_links: 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(_url) val = mark_safe("<a href='%s'>%s</a>"%(_url,field)) temp.append(val) new_data_list.append(temp) print('new_data_list',new_data_list) # 构造数据 [['jack', 44], ['mark', 33]] return render(request,'list_view.html', locals()) def add(self, request): return HttpResponse('add') def delete(self, request, id): return HttpResponse('delete') def change(self, request, id): return HttpResponse('change') def get_urls2(self): """构造 add/delete/change""" model_name = self.model._meta.model_name app_label = self.model._meta.app_label temp = [] temp.append(url(r'^$', self.list_view, name='%s_%s_list'%(app_label,model_name))) 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))) return temp @property def urls2(self): return self.get_urls2(), None, None class StarkSite(object): """site单例类""" 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) def get_urls(self): """构造一层urls app01/book""" temp = [] for model, stark_class_obj in self._registry.items(): print(model, 'stark_clas_obj', stark_class_obj) # 不同的model模型表 """ <class 'app01.models.UserInfo'> ----> <app01.starkadmin.UserConfig object at 0x00000072DDB65198> <class 'app01.models.Book'> ----> <stark.service.stark.ModelStark object at 0x00000072DDB65240> """ app_label = model._meta.app_label # app01 model_name = model._meta.model_name # book # temp.append(url(r'^%s/%s'%(app_label, model_name),([],None,None))) temp.append(url(r'^%s/%s/'%(app_label, model_name),stark_class_obj.urls2)) """ path('app01/userinfo/',UserConfig(Userinfo,site).urls2), path('app01/book/',ModelStark(Book,site).urls2), """ return temp @property def urls(self): # return [],None,None return self.get_urls(),None,None site = StarkSite() # 单例对象
4、模板层
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> <script src="/static/jQuery/jquery-3.2.1.min.js"></script> </head> <body> <h3>list页面</h3> <div class="container"> <div class="row"> <div class="col-md-9 col-lg-offset-1"> <table class="table table-bordered table-striped"> <tr> {% for header in header_list %} <th>{{ header }}</th> {% endfor %} </tr> {% for data in new_data_list %} <tr> {% for item in data %} <td>{{ item }}</td> {% endfor %} </tr> {% endfor %} </table> </div> </div> </div> <script type="text/javascript"> $('#choice').click(function () { if ($(this).prop('checked')){ //对象自身属性中是否具有指定的属性 $('.choice_item').prop("checked",true) }else{ $('.choice_item').prop("checked",false) } }) </script> </body> </html>