s14_示例:主机管理
- 示例(主机、业务线、应用 获取表单3方式、一对多、多对多操作,ajax)
# urls.py
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^business$', views.business),
url(r'^host$', views.host),
url(r'^test_ajax', views.test_ajax),
url(r'^app$', views.app),
url(r'^ajax_add_app$', views.ajax_add_app),
]
# models.py
from django.db import models
# Create your models here.
# class Foo(models.Model):
# name = models.CharField(max_length=1)
# row.b.fk.name
class Business(models.Model):
# id
caption=models.CharField(max_length=32)
code = models.CharField(max_length=32,null=True,default='SA')
# fk = models.ForeignKey('Foo')
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname= models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(protocol='ipv4',db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to = 'Business',to_field='id')
# 多对多
class Application(models.Model):
name=models.CharField(max_length=32)
r =models.ManyToManyField('Host')
# app01.application_r 表 id,application_id,host_id
# 手动创建
# class HostToApp(models.Model):
# hobj = models.ForeignKey(to='Host',to_field='nid')
# aobj = models.ForeignKey(to='Application',to_field='id')
# app01_hosttoapp 表 id,aobj_id,hobj_id
# views.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.
def business(request):
v1 = models.Business.objects.all()
# QuerySet[obj(id,caption,code),obj] 内部为对象
v2 = models.Business.objects.all().values('id','caption')
# QuerySet[{'id':1,'caption':'xxx'},{},{}] 内部为列表
v3 = models.Business.objects.values_list('id','caption')
# QuerySet[(1,xxx),(2,yyy)] 内部为元组
return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
"""
def host(request):
v1 = models.Host.objects.filter(nid__gt=0)
# for row in v1:
# print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id,sep='\t')
v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# models.Host.objects.后面跨表用双下划线: "__" ,为普通字符串,取值时为对象
# print(v2)
# QuerySet[{内部为字典},{字典}]
# for row in v2:
# print(row['nid'],row['hostname'],row['b_id'],row['b__caption'])
v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
"""
def host(request):
if request.method =='GET':
v1 = models.Host.objects.filter(nid__gt=0)
v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
b_list = models.Business.objects.all()
return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
elif request.method=='POST':
h = request.POST.get('hostname')
i = request.POST.get('ip')
p = request.POST.get('port')
b = request.POST.get('b_id')
models.Host.objects.create(hostname =h,
ip=i,
port=p,
b_id=b)
# return render(request,'host.html')
return redirect('/host')
def test_ajax(request):
import json
ret={'status':True,'error':None,'data':None}
try:
h = request.POST.get('hostname')
i = request.POST.get('ip')
p = request.POST.get('port')
b = request.POST.get('b_id')
if h and len(h) > 5:
models.Host.objects.create(hostname =h,
ip=i,
port=p,
b_id=b)
else:
ret['status'] = False
ret['error'] = 'too lower'
except Exception as e:
ret['status']= False
ret['error'] = '请求错误'
return HttpResponse(json.dumps(ret))
def app(request):
if request.method=='GET':
app_list=models.Application.objects.all()
# for row in app_list:
# print(row.name,row.r.all())
host_list = models.Host.objects.all()
return render(request,'app.html',{'app_list':app_list,'host_list':host_list})
elif request.method == 'POST':
app_name =request.POST.get('app_name')
host_list =request.POST.getlist('host_list')
print(app_name,host_list)
obj= models.Application.objects.create(name=app_name)
# obj 为刚才操作过的
obj.r.add(*host_list)
return redirect('/app')
import json
def ajax_add_app(request):
# 创建ret,待写
ret={'status':True,'error':None,'data':None}
app_name= request.POST.get('app_name')
host_list= request.POST.getlist('host_list')
obj= models.Application.objects.create(name=app_name)
obj.r.add(*host_list)
return HttpResponse(json.dumps(ret))
# business.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>业务线列表(对象)</h1>
<ul>
{% for row in v1 %}
<li>{{ row.id }} - {{ row.caption }} - {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(字典)</h1>
<ul>
{% for row in v2 %}
<li>{{ row.id }} - {{ row.caption }}</li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }}</li>
{% endfor %}
</ul>
</body>
</html>
# host.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.hide{display: none}
.shade{position: fixed;top:0;right: 0;left: 0;bottom: 0;
background: black;opacity: 0.6;z-index:100; }
.add-modal,.edit-modal{position: fixed;height: 300px;width:400px;top:100px;left: 50% ;
border:1px solid green;z-index: 101;background: white;margin-left: -200px;}
</style>
</head>
<body>
<h1>主机列表(对象)</h1>
<div>
<input id='add_host' type="button"value="添加">
</div>
<table border="1">
<thead>
<tr>
{# <th>主机ID</th>#}
<th>序号</th>
<th>主机名</th>
<th>IP</th>
<th>端口</th>
{# <th>业务线ID</th>#}
<th>业务线名称</th>
<th>操作</th>
{# <th>业务线编码</th>#}
</tr>
</thead>
<tbody>
{# {% for i in v1 %}#}
{% for row in v1 %}
<tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
// 将两个id 放置于此处,待用。
{# <td>{{ row.nid }}</td>#}
<td>{{ forloop.counter}}</td>
<td>{{ row.hostname }}</td>
<td>{{ row.ip }}</td>
<td>{{ row.port }}</td>
{# <td>{{ row.b_id }}</td>#}
<td>{{ row.b.caption }}</td>
<td><a class="edit">编辑</a>|<a class="delete">删除</a></td>
// 实现删除时,可通过Form表单或Ajax操作,Ajax操作时可找到页面当前行,进行删除。
{# <td>{{ row.b.code }}</td>#}
</tr>
{% endfor %}
{# {% endfor %}#}
</tbody>
</table>
<h1>主机列表(字典)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v2 %}
<tr hid="{{ row.id }}" bid="{{ row.b_id }}">
<td>{{ row.hostname }}</td>
<td>{{ row.b__caption }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<h1>主机列表(元组)</h1>
<table border="1">
<thead>
<tr>
<th>主机名</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v3 %}
<tr hid="{{ row.0 }}" bid="{{ row.2 }}">
<td>{{ row.1 }}</td>
<td>{{ row.3 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="shade hide"></div>
<div class="add-modal hide">
<form id='add_form'action="/host"method="POST">
// 未含验证功能,待Ajax
<div class="group"><input id="host" type="text"placeholder="主机名"name="hostname"></div>
<div class="group"><input id="ip" type="text"placeholder="ip"name="ip"></div>
<div class="group"><input id="port" type="text"placeholder="端口"name="port"></div>
<div class="group"><select name="b_id" id="sel">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select></div>
<input type="submit"value="提交">
<a id="ajax_submit" style="display: inline-block;padding: 5px;
color: white">Ajax提交</a>
<input id="cancel" type="button"value="取消">
<span id="erro_msg" style="color: red;"></span>
</form>
</div>
<div class="edit-modal hide">
<form id='edit_form'action="/host"method="POST">
<input type="text"name="nid" style="display: none;">
// 额外添加,修改后提交时获取host的id使用
<input type="text"placeholder="主机名"name="hostname">
<input type="text"placeholder="ip"name="ip">
<input type="text"placeholder="端口"name="port">
<select name="b_id" id="sel">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select>
<a id="ajax_sumit_edit">确认编辑</a>
</form>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
$(function () {
// 模态对话框
$('#add_host').click(function () {
$('.shade,.add-modal').removeClass('hide');
});
$('#cancel').click(function () {
$('.shade,.add-modal').addClass('hide');
})
});
// Ajax 提交
$('#ajax_submit').click(function () {
$.ajax({
url:'/test_ajax',
type:"POST",
{# data:{'hostname':$('#host').val(),#}
{# 'ip':$('#ip').val(),#}
{# 'port':$('#port').val(),#}
{# 'b_id':$('#sel').val()#}
{# },#}
data:$('#add_form').serialize(),
success: function (data) {
var obj =JSON.parse(data);
if (obj.status){
location.reload();
}else{
$("#erro_msg").text(obj.error);
}
}
})
});
// Ajax 编辑
$('.edit').click(function () {
$('.shade,.edit-modal').removeClass('hide');
// 只实现了多选,其他待添加
var bid= $(this).parent().parent().attr('bid');
// ** 获取编辑行修改前的 business 的 id
var nid= $(this).parent().parent().attr('hid');
// @@ 获取当前编辑行host的 id
console.log(bid,nid);
$('#edit_form').find('select').val(bid);
// ** 将 bid 赋值给模态对话框 select标签:选中状态
$('#edit_form').find('input[name="nid"]').val(nid);
// @@ 将当前编辑的host id 赋值给 模态框 额外添加的input框
$.ajax({
url:'',
data:$('#edit_form').serialize()
});
// models.Host.object.filter(nid=nid).update()
});
</script>
</body>
</html>
# app.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.host-tag{display: inline-block;padding: 3px;border: 1px solid red;}
</style>
<style>
.hide{display: none}
.shade{position: fixed;top:0;right: 0;left: 0;bottom: 0;
background: black;opacity: 0.6;z-index:100; }
.add-modal,.edit-modal{position: fixed;height: 300px;width:400px;top:100px;left: 50% ;
border:1px solid green;z-index: 101;background: white;margin-left: -200px;}
</style>
</head>
<body>
<h1>****** 多对多*******</h1>
<h1>应用列表</h1>
<div>
<input id='add_app' type="button"value="add">
</div>
<table border="1">
<thead>
<tr>
<td>应用名称</td>
<td>应用主机列表</td>
</tr>
</thead>
<tbody>
{% for app in app_list %}
<tr aid = '{{ app.id }}'>
// 定制aid 为编辑使用
<td>{{ app.name }}</td>
<td>
{% for host in app.r.all %}
<span class='host-tag' hid="{{ host.nid }}">{{ host.hostname }}</span>
// hid="{{ host.nid }} 额外添加,为编辑使用准备
// 后面添加 删除 图标,进行删除,待写。
{% endfor %}
</td>
<td><a class="edit">编辑</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="shade hide"></div>
<div class="add-modal hide">
<form id='add_form' action="/app" method="POST">
<div class="group"><input id="app_name" type="text"placeholder="应用名称"name="app_name"></div>
<div class="group"><select name="host_list" id="host_list" multiple>
{% for op in host_list %}
<option value="{{ op.nid }}">{{ op.hostname }}</option>
{% endfor %}
</select></div>
<input type="submit"value="提交">
<input id="add_submit_ajax" type="button"value="ajax提交">
</form>
</div>
<div class="edit-modal hide">
<form id='edit_form' action="/host" method="POST">
<input type="text"name="nid" style="display: none;">
<input type="text"placeholder="应用名称"name="app">
<select name="host_list" multiple>
{% for op in host_list %}
<option value="{{ op.nid }}">{{ op.hostname }}</option>
{% endfor %}
</select>
<a id="ajax_sumit_edit">编辑</a>
</form>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
$(function () {
$('#add_app').click(function () {
$('.shade,.add-modal').removeClass('hide');
});
$('#cancel').click(function () {
$('.shade,.add-modal').addClass('hide');
});
$("#add_submit_ajax").click(function () {
$.ajax({
url:'/ajax_add_app',
{# data:{'user':123,'host_list':[1,2,3,4]},#}
data:$('#add_form').serialize(),
type:'POST',
dataType:JSON,
traditional:true,
// 添加后才能处理: []
success: function (obj) {
console.log(obj);
// 拿到ret进行判断、跳转,待写。
},
error: function () {
}
});
});
// 编辑功能
$('.edit').click(function () {
$('.edit-modal,.shade').removeClass('hide');
// 仅做了 主机 多选项,其他待写。
var hid_list=[];
$(this).parent().prev().children().each(function () {
// 对span标签循环,获取hid
{# var text= $(this).text();#} // 获取主机名
var hid = $(this).attr('hid'); // 获取value
hid_list.push(hid)
});
//select 设置多选后,value 是个列表
$('#edit_form').find('select').val(hid_list);
//发送到后台 obj=model.Application.objects.get(id=aid)
// obj.name= New name
// obj.save()
// obj.r.set([1,2,3,])
});
});
</script>
</body>
</html>