stark - 增、删、改
一、效果图
二、增、删、改
知识点:
1.解决代码重用
{% include 'form.html' %} 2.自定制配置modelform
每张表,就可自定义配置 labels , widges...
class BookModelForm(ModelForm):
class Meta:
model = Book
fields = "__all__"
labels = {
"title": '书籍名称',
"price": '价格',
}
...
modelform_class = BookModelForm
ModelFormDemo = self.get_modelform_class() 配置样式,由于不确定字段,得在前端玩! 3.change_view()
注意 instance,否则为添加
form = ModelFormDemo(request.POST, instance=edit_obj)
if form.is_valid():
form.save()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
<script src="/static/js/jquery-1.12.4.min.js"></script>
<style type="text/css">
input,select {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.error{
color: red;
} </style> </head>
<body>
<h3>添加页面</h3> {% include 'form.html' %} </body>
</html>
add_view.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
<script src="/static/js/jquery-1.12.4.min.js"></script>
<style type="text/css">
input,select {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.error{
color: red;
} </style> </head>
<body>
<h3>编辑页面</h3> {% include 'form.html' %} </body>
</html>
change_view.html
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-1">
<form action="" method="post" novalidate>
{% csrf_token %}
{% for field in form %}
<div>
<label for="">{{ field.label }}</label>
{{ field }} <span class="error pull-right">{{ field.errors.0 }}</span>
</div>
{% endfor %} <button type="submit" class="btn btn-info">btn</button>
</form> </div>
</div> </div>
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>删除页面</h3>
<form action="" method="post">
{% csrf_token %}
<button>确认删除吗?</button>
<a href="{{ url }}">取消</a>
</form> </body>
</html>
delete_view.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
<script src="/static/js/jquery-1.12.4.min.js"></script>
<style type="text/css"> </style>
</head>
<body> <h4>数据列表</h4> <div class="container">
<div class="row">
<div class="col-md-9">
<a href="{{ add_url }}" class="btn btn-primary">添加数据</a>
<table class="table table-bordered table-striped">
<thead>
<tr>
{% for item in header_list %}
<th>{{ item }}</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> <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>
list_view.html
app01/stark.py
# -*- coding:utf-8 -*-
from stark.service import stark
from .models import *
from django.forms import ModelForm class BookModelForm(ModelForm):
class Meta:
model = Book
fields = "__all__"
labels = {
"title": '书籍名称',
"price": '价格',
'publishDate': '出版日期'
} class BookConfig(stark.ModelStark): list_display = ['title', 'price','publishDate']
list_display_links = ['title']
modelform_class = BookModelForm stark.site.register(Book, BookConfig)
stark.site.register(Publish)
stark.site.register(Author)
stark.site.register(AuthorDetail)
stark/service/stark.py
from django.conf.urls import url
from django.shortcuts import HttpResponse, reverse, redirect, render
from django.utils.safestring import mark_safe
from django.urls import reverse
from django.forms import ModelForm class ModelStark(object):
list_display = ["__str__"]
list_display_links = []
modelform_class = [] def __init__(self, model, site):
self.model = model
self.site = site def edit(self, obj=None, header=False):
if header:
return "操作" _url = self.get_change_url(obj)
return mark_safe("<a href='%s'>编辑</a>" % _url) def deletes(self, obj=None, header=False):
if header:
return '操作' _url = self.get_delete_url(obj)
return mark_safe("<a href='%s'>删除</a>" % _url) 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 get_modelform_class(self):
if not self.modelform_class:
class ModelFormDemo(ModelForm):
class Meta:
model = self.model
fields = "__all__"
# 得在前端玩
# widgets = {
# "title":wid.TextInput(attrs={'class':'form-control'})
# }
# 得自定制去配置
# labels = {
# "title":'书籍名称'
# }
return ModelFormDemo
else:
return self.modelform_class def add_view(self, request):
ModelFormDemo = self.get_modelform_class()
form = ModelFormDemo() if request.method == 'POST':
form = ModelFormDemo(request.POST)
if form.is_valid():
form.save()
return redirect(self.get_list_url()) return render(request, 'add_view.html', locals()) def delete_view(self, request, delete_id):
url = self.get_list_url() if request.method == 'POST':
self.model.objects.filter(pk=delete_id).delete()
return redirect(url) return render(request, 'delete_view.html', locals()) def change_view(self, request, change_id):
ModelFormDemo = self.get_modelform_class()
edit_obj = self.model.objects.filter(pk=change_id).first()
form = ModelFormDemo(instance=edit_obj) if request.method == "POST":
form = ModelFormDemo(request.POST, instance=edit_obj)
if form.is_valid():
form.save()
return redirect(self.get_list_url()) return render(request,'change_view.html', locals()) def new_list_play(self):
temp = []
temp.append(ModelStark.checkbox)
temp.extend(self.list_display)
temp.append(ModelStark.edit)
temp.append(ModelStark.deletes) return temp def get_change_url(self, obj):
model_name = self.model._meta.model_name
app_lable = self.model._meta.app_label _url = reverse("%s_%s_change" % (app_lable, model_name), args=(obj.pk,)) 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_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_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_view(self, request):
data_list = self.model.objects.all() # 构建表头
header_list = []
# header_list = ['选择','pk',...'操作','操作']
for field in self.new_list_play():
if callable(field):
val = field(self, header = True)
else:
if field == "__str__":
val = self.model._meta.model_name.upper()
else: # 根据str 拿字段对象 取中文
val = self.model._meta.get_field(field).verbose_name header_list.append(val) # 构建表单
new_data_list = []
for data in data_list:
temp = []
for field in self.new_list_play(): # ['title','price'] 字符串找对象得属性 反射
print('field:', field)
if callable(field):
val = field(self, data)
else:
val = getattr(data, field) if field in self.list_display_links:
_url = self.get_change_url(data)
val = mark_safe("<a href='%s'>%s</a>" % (_url, val)) temp.append(val) new_data_list.append(temp) # [['yuan', 12], ['alex', 18], ['egon', 22]] # 构建一个查看url
add_url = self.get_add_url()
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 temp.append(url(r'add/', self.add_view, name="%s_%s_add" % (app_label, model_name)))
temp.append(url(r'(\d+)/delete/', self.delete_view, name="%s_%s_delete" % (app_label, model_name)))
temp.append(url(r'(\d+)/change/', self.change_view, name="%s_%s_change" % (app_label, model_name)))
temp.append(url(r'^$', self.list_view, name="%s_%s_list" % (app_label, model_name))) return temp @property
def urls2(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) def get_urls(self):
temp = [] # 模型表,配置类对象
for model, stark_class_obj in self._registry.items():
model_name = model._meta.model_name
app_label = model._meta.app_label # 分发增删改查
temp.append(url(r'%s/%s/'%(app_label,model_name), stark_class_obj.urls2)) return temp @property
def urls(self): return self.get_urls(), None, None site = StarkSite()
stark - 增、删、改的更多相关文章
- C# ADO.NET (sql语句连接方式)(增,删,改)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- 好用的SQL TVP~~独家赠送[增-删-改-查]的例子
以前总是追求新东西,发现基础才是最重要的,今年主要的目标是精通SQL查询和SQL性能优化. 本系列主要是针对T-SQL的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础] ...
- iOS FMDB的使用(增,删,改,查,sqlite存取图片)
iOS FMDB的使用(增,删,改,查,sqlite存取图片) 在上一篇博客我对sqlite的基本使用进行了详细介绍... 但是在实际开发中原生使用的频率是很少的... 这篇博客我将会较全面的介绍FM ...
- iOS sqlite3 的基本使用(增 删 改 查)
iOS sqlite3 的基本使用(增 删 改 查) 这篇博客不会讲述太多sql语言,目的重在实现sqlite3的一些基本操作. 例:增 删 改 查 如果想了解更多的sql语言可以利用强大的互联网. ...
- ADO.NET 增 删 改 查
ADO.NET:(数据访问技术)就是将C#和MSSQL连接起来的一个纽带 可以通过ADO.NET将内存中的临时数据写入到数据库中 也可以将数据库中的数据提取到内存中供程序调用 ADO.NET所有数据访 ...
- MVC EF 增 删 改 查
using System;using System.Collections.Generic;using System.Linq;using System.Web;//using System.Data ...
- 第18课-数据库开发及ado.net 连接数据库.增.删.改向表中插入数据并且返回自动编号.SQLDataReade读取数据
第18课-数据库开发及ado.net 连接数据库.增.删.改向表中插入数据并且返回自动编号.SQLDataReade读取数据 ADO.NET 为什么要学习? 我们要搭建一个平台(Web/Winform ...
- django ajax增 删 改 查
具于django ajax实现增 删 改 查功能 代码示例: 代码: urls.py from django.conf.urls import url from django.contrib impo ...
- StringBuilder修改字符串内容,增,删,改,插
package seday01;/** * 字符串不变对象特性只针对字符串重用,并没有考虑修改操作的性能.因此String不适合频繁修改内容. * 若有频繁修改操作,使用StringBuilder来完 ...
- python基础中的四大天王-增-删-改-查
列表-list-[] 输入内存储存容器 发生改变通常直接变化,让我们看看下面列子 增---默认在最后添加 #append()--括号中可以是数字,可以是字符串,可以是元祖,可以是集合,可以是字典 #l ...
随机推荐
- 消息中间件-ActiveMQ入门实例
1.下载ActiveMQ: http://activemq.apache.org/download-archives.html 2.运行ActiveMQ 解压缩apache-activemq-5.5. ...
- ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)
前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...
- oracle如何将am,pm时间字符串改为时间格式
问题: 解决办法: 1.param["OPT_DATE"] = DateTime.Parse(dt.Rows[0]["CREATED_ON"].ToString ...
- Tomcat 8(九)解读Tomcat组件的生命周期(Lifecycle)
Tomcat 8(七)解读Bootstrap介绍过.运行startup.bat.将引发Tomcat一连串组件的启动.事实上这一连串启动是通过组件的生命周期(Lifecycle)实现的 今天来看看Lif ...
- Animy.js,自己编写的功能丰富的html动画库
近期由于项目须要.本人制作了一款js的动画插件.能够用于完毕各种js动画.比方移动.拉升.变色等等,全部动画经常使用的功能都已经实现,比方播放.暂停.停止.循环.加速.减速.反向播放.缓动.路径动画. ...
- 甘特图生产排程(APS)定制开发
高速开发完毕APS的数据可视化.订单展示.资源调度.智能排程等差点儿所有功能模块. 自己主动智能排程功能 提供专业需求分析师及开发团队,按需开发"全自己主动智能排程"这一APS的主 ...
- mybatis由浅入深day02_课程复习_1订单商品数据模型分析
mybatis第二天 高级映射 查询缓存 和spring整合 课程复习: mybatis是什么? mybatis是一个持久层框架,mybatis是一个不完全的ORM框架.sql语句需要程序员自己去编 ...
- cut的用法【转】
cut是一个选取命令,就是将一段数据经过分析,取出我们想要的.一般来说,选取信息通常是针对“行”来进行分析的,并不是整篇信息分析的. (1)其语法格式为:cut [-bn] [file] 或 cut ...
- android 仿QQ手机版
千人2群开启,欢迎大家围观打酱油,群号145667827 您当前位置 : JavaApk-安卓应用游戏源码服务专家 » QQ » Android项目源码界面超级华丽的仿QQ最新版本 Andro ...
- CentOS 6.3下Samba服务器的安装与配置详解
一.简介 Samba是一个能让Linux系统应用Microsoft网络通讯协议的软件,而SMB是Server Message Block的缩写,即为服务器消息块 ,SMB主要是作为Microsoft的 ...