冰冻三尺非一日之寒--web框架Django(三)
from django.shortcuts import render, HttpResponse, redirect
from app01 import models
import json # Create your views here.
def business(request):
v1 = models.Business.objects.all() v2 = models.Business.objects.all().values('id', 'caption', 'code') v3 = models.Business.objects.all().values_list('id', 'caption', 'code') return render(request, 'business.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 redirect('/host') def test_ajax(request): 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'] = "太短了"
except Exception as e:
ret['status'] = False
ret['error'] = '请求错误'
return HttpResponse(json.dumps(ret)) views.py
View.py
from django.db import models # Create your models here. class Business(models.Model):
caption = models.CharField(max_length=32)
code = models.CharField(max_length=32) class Host(models.Model): nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
ip = models.GenericIPAddressField(db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business",to_field='id') models.py
models.py
<!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, .delete-modal {
position: fixed;
height: 300px;
width: 400px;
top: 100px;
left: 50%;
z-index: 101;
border: 1px solid red;
background: white;
margin-left: -200px;
}
</style>
</head>
<body>
<h1>主机列表(对象)</h1>
<div>
<input id="add_host" type="button" value="添加"/>
</div>
<table border="">
<thead>
<tr>
<th>序号</th>
<th>主机名</th>
<th>IP</th>
<th>端口</th>
<th>业务线名称</th>
<th>操作</th>
</tr>
</thead>
<tbody> {% for row in v1 %}
<tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
<td>{{ forloop.counter }}</td>
<td>{{ row.hostname }}</td>
<td>{{ row.ip }}</td>
<td>{{ row.port }}</td>
<td>{{ row.b.caption }}</td>
<td>
<a class="edit">编辑</a>|<a class="delete">删除</a>
</td>
</tr>
{% endfor %} </tbody>
</table> <h1>主机列表(字典)</h1>
<table border="">
<thead>
<tr>
<th>主机名</th>
<th>业务线名称</th>
</tr>
</thead>
<tbody>
{% for row in v2 %}
<tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
<td>{{ row.hostname }}</td>
<td>{{ row.b__caption }}</td>
</tr>
{% endfor %} </tbody>
</table>
<h1>主机列表(元组)</h1>
<table border="">
<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" method="POST" action="/host">
<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 id="sel" name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select>
</div> <input type="submit" value="提交"/>
<a id="ajax_submit">悄悄提交</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" method="POST" action="/host">
<input type="text" name="nid" style="display:none"/>
<input type="text" placeholder="主机名" name="hostname"/>
<input type="text" placeholder="IP" name="ip"/>
<input type="text" placeholder="端口" name="port"/>
<select name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select>
<a id="ajax_submit_edit">确认编辑</a>
<input id="ajax_submit_cancel" type="button" value="取消"/>
</form>
</div>
<div class="delete-modal hide">
<form id="delete_form" method="POST" action="/host">
<input type="text" name="nid" style="display:none"/>
<input type="text" placeholder="主机名" name="hostname"/>
<input type="text" placeholder="IP" name="ip"/>
<input type="text" placeholder="端口" name="port"/>
<select name="b_id">
{% for op in b_list %}
<option value="{{ op.id }}">{{ op.caption }}</option>
{% endfor %}
</select>
<a id="submit_delete">确认删除</a>
<input id="submit_cancle" type="button" value="取消"/>
</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_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);
}
}
})
}); $('.edit').click(function () {
$('.shade,.edit-modal').removeClass('hide'); var bid = $(this).parent().parent().attr('bid');
var nid = $(this).parent().parent().attr('hid'); $('#edit_form').find('select').val(bid);
$('#edit_form').find('input[name="nid"]').val(nid);
// 修改
/*
$.ajax({
data: $('#edit_form').serialize()
});
*/
// modeletes.Host.objects.filter(nid=nid).update()
});
$('#ajax_submit_cancel').click(function () {
$('.shade,.edit-modal').addClass('hide');
}); $('.delete').click(function () {
$('.shade,.delete-modal').removeClass('hide'); var bid = $(this).parent().parent().attr('bid');
var nid = $(this).parent().parent().attr('hid'); $('#delete_form').find('select').val(bid);
$('#delete_form').find('input[name="nid"]').val(nid);
});
$('#submit_cancle').click(function () {
$('.shade,.delete-modal').addClass('hide');
}); })
</script> </body>
</html> host.html
host.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 }}- {{ row.code }}</li>
{% endfor %}
</ul>
<h1>业务线列表(元组)</h1>
<ul>
{% for row in v3 %}
<li>{{ row.0 }} - {{ row.1 }}- {{ row.2 }}</li>
{% endfor %}
</ul>
</body>
</html> business.html
business
"""s14day20 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
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),
# url(r'^business_add', views.business),
] url.py
url.py
8、外键:
"""s14day20 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
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),
# url(r'^business_add', views.business),
] url.py
url.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;
background-color: palevioletred;
}
.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%;
z-index: 101;
border: 1px solid red;
background: white;
margin-left: -200px;
}
</style>
</head>
<body> <h1>应用列表</h1>
<div>
<input id="add_app" type="button" value="添加" />
</div>
<table border="">
<thead>
<tr>
<td>应用名称</td>
<td>应用主机列表</td>
</tr>
</thead>
<tbody>
{% for app in app_list %}
<tr aid="{{ app.id }}">
<td>{{ app.name }}</td>
<td>
{% for host in app.r.all %}
<span class="host-tag" hid="{{ host.nid }}"> {{ host.hostname }} </span>
{% 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" method="POST" action="/app">
<div class="group">
<input id="app_name" type="text" placeholder="应用名称" name="app_name" />
</div>
<div class="group">
<select id="host_list" name="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" method="POST" action="/host">
<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_submit_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);
},
error: function () { } })
}); $('.edit').click(function(){ $('.edit-modal,.shade').removeClass('hide'); var hid_list = [];
$(this).parent().prev().children().each(function(){
var hid = $(this).attr('hid');
hid_list.push(hid)
}); $('#edit_form').find('select').val(hid_list);
// 如果发送到后台
//
/*
obj = models.Application.objects.get(id=ai)
obj.name = "新Name"
obj.save()
obj.r.set([1,2,3,4])
*/ }) }) </script>
</body>
</html> app.html
app.html
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
import json
# Create your views here. def business(request):
v1 = models.Business.objects.all()
# QuerySet
# [obj(id,caption,code),obj(id,caption,code),obj(id,caption,code) ] v2 = models.Business.objects.all().values('id','caption')
# QuerySet
# [{'id':1,'caption': '����'},{'id':1,'caption': '����'},...] v3 = models.Business.objects.all().values_list('id','caption')
# QuerySet
# [(1������),(2,����)]
return render(request, 'business.html', {'v1': v1,'v2': v2, 'v3': v3}) # def host(request):
# v1 = models.Host.objects.filter(nid__gt=0)
# # QuerySet [hostobj(ip.host,����һ������(..)),]
# # 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')
# # print(row.b.fk.name)
# # return HttpResponse("Host")
# v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
# # QuerySet: [ {} ]
# # print(v2)
# # 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')
# # QuerySet: [ {} ]
# # print(v2)
# 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=models.Business.objects.get(id=b)
# )
models.Host.objects.create(hostname=h,
ip=i,
port=p,
b_id=b
)
return redirect('/host') def test_ajax(request): 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'] = "太短了"
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.r.add(*host_list) return redirect('/app') def ajax_add_app(request):
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)) views.py
View.py
冰冻三尺非一日之寒--web框架Django(三)的更多相关文章
- 冰冻三尺非一日之寒--web框架Django
1.JS 正则 test - 判断字符串是否符合规定的正则 rep = /\d+/; rep.test("asdfoiklfasdf89asdfasdf ...
- 冰冻三尺非一日之寒--web框架Django(翻页、cookie)
第二十一章 cookie 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, ...
- python运维开发(十七)----jQuery续(示例)web框架django
内容目录: jQuery示例 前端插件 web框架 Django框架 jQuery示例 dom事件绑定,dom绑定在form表单提交按钮地方都会绑定一个onclick事件,所有查看网站的人都能看到代码 ...
- Web框架——Django笔记
Web框架--Django笔记 MVC和MTV MVC:Model.View.Controller MTV:Model.Template.View Django--MTV 1.创建Django程序 ...
- Python3.5学习十八 Python之Web框架 Django
Python之Web框架: 本质:Socket 引用wsgiref创建web框架 根据web框架创建过程优化所得: 分目录管理 模板单独目录 执行不同函数单独存入一个方法py文件 Web框架的两种形式 ...
- Web框架-Django基础
一.django简介 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的软件设计模式,即模型M,视图V和控制器C.它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内 ...
- 利用python web框架django实现py-faster-rcnn demo实例
操作系统.编程环境及其他: window7 cpu python2.7 pycharm5.0 django1.8x 说明:本blog是上一篇blog(http://www.cnblogs.co ...
- web框架---django
15:31:14一.web框架1.框架:即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. ...
- Python 17 web框架&Django
本节内容 1.html里面的正则表达式 2.web样式简介 3.Django创建工程 Html里的正则表达式 test 用来判断字符串是否符合规定的正则 rep.test('....') ...
随机推荐
- 如何在Windows Server 2008 R2 SP1安装Redis-x64-3.2.100,并且自动注册服务
1.官网:http://redis.io/ 2.下载地址:https://github.com/MSOpenTech/redis/releases 3.最新的安装包: 4.点击msi文件开始安装. 5 ...
- Web Service随笔
什么是Web Service? WebService是一个SOA(面向服务的编程)的架构,它是不依赖于语言,不依赖于平台,可以实现不同的语言间的相互调用,通过Internet进行基于Http协议的网络 ...
- 【原】低版本MyEclipse整合高版本Tomcat
[使用工具] 1.MyEclipse_6.0.1GA_E3.3.1_FullStackInstaller 2.Tomcat 7.0 [问题描述] 直接在MyEclipse中整合,因为这个版本的MyEc ...
- ABAP关键字SUBMIT的简单例子和学习小记
网上有关SUBMIT实现程序调用的例子稍显复杂,而相关的参考和解释则不是很完善.本文给出一个SUBMIT的小示例程序(代码见文末),实现了最简单的程序间调用及返回值,以及SAP官方文档中相关内容的翻译 ...
- npm更新到最新版本的方法
打开命令行工具 npm -v 查看是否是最新版本 如果不是 运行npm i npm g 升级 打开C:\Users\用户名用户目录找到node_modules 文件夹下的npm文件夹,复制一份 打开n ...
- 聊天气泡 button backgroundImage uiimage 拉伸 stretchableImageWithLeftCapWidth: 方法的使用
- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCap ...
- fastjson 混淆注意事项
使用fastjson 注意事项,主要表现: 1.加了符号Annotation 的实体类,一使用就会奔溃 2.当有泛型属性时,一使用就奔溃 在调试的时候不会报错,当你要打包签名混淆包的时候,就会出现上述 ...
- 3D坦克大战游戏源码
3D坦克大战游戏源码,该游戏是基于xcode 4.3,ios sdk 5.1开发.在xcode4.3.3上完美无报错.兼容ios4.3-ios6.0 ,一款ios平台上难得的3D坦克大战游戏源码,有2 ...
- C#语言基础——函数
函数一个较大的程序一般应分为若干个程序块,每一个模块用来实现一个特定的功能.所有的高级语言中都有子程序这个概念,用子程序实现模块的功能.在C#语言中,子程序的作用是由一个主函数和若干个函数构成.由主函 ...
- linux rsync配置文件参数详解
一.全局参数 在[moudle]之前的参数都是全局参数,也可以在全局参数下定义部分模块参数,这时该参数的值就是所有模块的默认值. port:指定后台程序使用的端口号,默认是873 logfile:指定 ...