8 stark组件 展示数据
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>}
"""
starkadmin.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 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() # 单例对象
stark/service/stark.py
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>
8 stark组件 展示数据的更多相关文章
- day 66 crm(3) 自创组件stark界面展示数据
前情提要: 接着上一节的.stark自创组件的展示效果编写 展示数据 一:按照默认自带数据展示 即无一对一,一对多 1:先获取queryset对象 2:获取当前操作模型表对象数据 注意:list_d ...
- CRM项目之stark组件
. stark也是一个app(用startapp stark创建),目标时把这个做成一个可以拔插的组件 . setting文件下INSTALLED_APPS 路径要配置好(app的注册) . 写好si ...
- day 70 crm(7):stark组件调用,以及权限分配
前情提要: 复习: 1: orm !!!!! 2: session 3: django 4: 前端在复习 5: 复习中间件 学习的stark 的组件调用,以及权限的应用 一:权限的概念, 1: ...
- stark组件(4):列表定义列,展示数据库数据
效果图: 一.Stark组件 stark/service/core_func.py from django.urls import re_path from django.shortcuts impo ...
- 【django之stark组件】
一.需求 仿照django的admin,开发自己的stark组件.实现类似数据库客户端的功能,对数据进行增删改查. 二.实现 1.在settings配置中分别注册这三个app # Applicatio ...
- django 之 stark组件
----------------------------------------------------------------烦恼没完没了,内心动荡不安,呜呼哀哉. 一.有个特殊的需求,需要用sta ...
- stark组件的分页,模糊查询,批量删除
1.分页组件高阶 2.整合展示数据showlist类 3.stark组件之分页 3.stark组件之search模糊查询 4.action批量处理数据 4.总结 1.分页组件高阶 1.分页的class ...
- 10.18正式开发stark组件*(三)
2018-10-18 19:15:54 等这个stark组件做完了再上传到github上面,然后再整理博客!这就到周末啦! 因为models导入的时候出现bug,所以只有源码没有测试数据! 源码都有注 ...
- stark组件开发之列表页面定制列
先看一张页面展示的效果图: 看一看我的 model 表!是什么样子: 看一看数据库是什么样子: 看 页面展示图,有表头. 有数据.模型表中,每一个字段, 都指定了 verbose_name. 如何解 ...
随机推荐
- C++发展概述、优缺点及应用领域
个人观点(C++虽功能强大,但是底层还是调用C,C++为了吸引更多的C程序员,功能过于丰富且复杂,一定程度上反而降低了可编程的实用性.但是不可否认C++ 也是一门艺术.) C++是一门以C为基础发展而 ...
- django项目设计
我们以前是只建立一个项目只建立一个app,如果我们要建立多个app的时候 并且这个app要写很多额视图的函数views内函数,要是建立很多种的时候就会造成很冗杂,不美观 我们未来增强解耦性,就把那个 ...
- windows下搭建vue开发环境
Vue.js是一套构建用户界面的 “渐进式框架”.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注视图层,并且非常容易学习,非常容易与其它库或已有项目整合.2016 ...
- 铁乐学python_day18-19_面向对象编程1
以下笔记绝大部分(百分之80或以上)摘自我的授课老师之一:老男孩教育中的景老师. 她上课讲的知识点由浅入深,引人入胜,听她的课完全不会感觉到困阿,而且不知不觉中就感觉掌握了. 她的博客是: http: ...
- Virtual PC局域网共享速度慢的解决半法。转
HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DisableTaskOffload 新建字符串,名:DisableTaskOffloa ...
- November 16th 2016 Week 47th Wednesday
Success is falling nine times and getting up ten. 成功就是哪怕跌倒九次,也要在第十次爬起来. For most of us, we may choos ...
- n = 3 , while n , continue
- python第十六课——ascii码
2.ascii码 美国设计出来的一张编码表,将涉及的字符都编号了,底层仍然还是进行二进制的运算: 记住:3个范围段 1).'0' --> 码值:48 2).'A' --> 码值:65 3) ...
- flex使用学习
1.指定容器为flex布局 display:flex 行内元素也可以使用Flex布局. display: inline-flex; 注意,设为Flex布局以后,子元素的float.clear和vert ...
- two sum[easy]
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...