一个初学者的辛酸路程-依旧Django

回顾:

1、Django的请求声明周期?
 
请求过来,先到URL,URL这里写了一大堆路由关系映射,如果匹配成功,执行对应的函数,或者执行类里面对应的方法,FBV和CBV,本质上返回的内容都是字符串,通过复杂字符串来说比较麻烦,就写到文件里面,通过OPEN函数打开再返回给用户,所以模板可以任何文件名。
后台一定要说,模板里面有特殊的标记,待特殊标记的模板+值进行渲染,得到最终给用户的字符串。
总结为:
路由系统==》视图函数==》获取模板+数据==>渲染==》最终字符串返回给用户。
 
2、路由系统
有哪几种对应?
1、URL对应函数,可以包含正则
/index/    ==>  函数(参数)或者类 .as_view() (参数)
2、上面是定时的,所以有正则
/detail/(\d+)  ==> 函数(参数)或类  .as_vies() (参数)
3、基于问号和参数名
/detail/(?P<nid>\d+)  ==> 函数(参数)或类  .as_vies() (参数)
4、路由的分发,使用include和前缀来区分
/detail/ ==> include("app01.urls")
5、规定路由对应的名字
/detail/   name="a1"   ==> include("app01.urls")
  • 视图中: 使用reverse函数来做
  • 模板种: {% url  "a1" %}
3、视图函数
FBV 和CBV的定义:
FBV就是函数,CBV就是类
 
FBV:
def  index(request,*args,**kwargs):
pass
 
CBV: 类
class Home(views.View):
  • def get(self,request,*args,**kwargs):
  • ..
 
 
获取用户请求中的数据:
  •     request.POST.get
  • request.GET.get
  • request.FILES.get()
  • #checkbox复选框
  • ......getlist()
  • request.path_info
 
  • 文件对象 = request.FILES.get()  或者input的name
  • 文件对象.name
  • 文件对象.size
  • 文件对象.chunks()
 
  • #<form  特殊的设置></form>
给用户返回数据:
  • render(request,HTML模板文件的路径,{‘k1’:[1,2,3,4],'k2':{'name':'da','age':73}})
  • redirect("URL") 就是我们写的URL,也可以是别的网站
  • HttpResponse(字符串)
4、模板语言
  • render(request,HTML模板文件的路径,{'obj':1234,‘k1’:[1,2,3,4],'k2':{'name':'da','age':73}})
如何在HTML去取值
<html>
<body>
  •      <h1> {{ obj }}</h1>
  • <h1> {{ k1.3 }}</h1>
  • <h1> {{ k2.name}}</h1>
  • 循环列表
  • {% for i in k1 %}
  • <p> {{ i}}</p>
  • {% endfor%}
  • 循环字典
  • {% for row in k2.keys %}
  • {{ row  }}
  • {% endfor %}
  • {% for row in k2.values %}
  • {{ row  }}
  • {% endfor %}
  • {% for k,v in k2.items %}
  • {{ k  }}--{{v}}
  • {% endfor %}
</body>
</html>
 
5、数据库取数据  ORM(关系对象映射,写的类自动转为SQL语句取数据,去到以后转换成对象给我)
两个操作:
1、创建类和字段
class User(models.Model):
  • age = models.IntergerField()   整数不用加长度,没有一点用
  •  name = models.CharField(max_length=12) 字符长度,只接受12个字符
 
  • 生成数据库结构:
  • python manage.py  makemigrations
  • python manage.py migrate
  • 如果没有生成,那就是settings.py里要注册app,不然会出问题,数据库创建不了。
 
2、操作
models.User.objects.create(name="test",age=18)
传个字典
dic = {'name': 'xx' , 'age': 19}
models.User.objects.create(**dic)
 
obj = models.User(name="test",age=18)
obj.save()
models.User.objects.filter(id=1).delete()
models.User.objects.filter(id__gt=1).update(name='test',age=23)
传字典也可以
dic = {'name': 'xx' , 'age': 19}
models.User.objects.filter(id__gt=1).update(**dic)
 
models.User.objects.filter(id=1)
models.User.objects.filter(id__gt=1)
models.User.objects.filter(id__lt=1)
models.User.objects.filter(id__lte=1)
models.User.objects.filter(id__gte=1)
models.User.objects.filter(id=1,name='root')
换成字典也可以传
dic = {'name': 'xx' , 'age': 19}
models.User.objects.filter(**dic)
 
外键:
 
 
 
正式开干
1、创建1对多表结构
执行创建表命令,出现下面报错
 
文件在于没有注册app
创建表,表信息如下:
  1. from django.db import models
 
  1. # Create your models here.
 
  1. #业务线
  1. class Business(models.Model):
  1.     #默认有个id列
  1.     caption = models.CharField(max_length=32)
 
 
  1. class Host(models.Model):
  1.     nid = models.AutoField(primary_key=True)
  1.     hostname = models.CharField(max_length=32,db_index=True)
  1.     ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
  1.     port = models.IntegerField()
  1.     b = models.ForeignKey(to="Business",to_field='id')
执行下面命令创建表结构
 
如果我创建完了以后呢,然后我又加了一条语句,会报错呢?
执行下面命令,会有2种选择,
 
所以可以修改为这个
  1. code = models.CharField(max_length=32,null=True,default="SA")
 
具体操作:
1、HTML
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1. </head>
  1. <body>
  1.     <h1>业务线列表(对象方式)</h1>
  1.     <ul>
  1.         {% for row in v1 %}
  1.             <li>{{ row.id }}-{{ row.caption }}-{{ row.code }}</li>
  1.         {% endfor %}
  1.     </ul>
  1.     <h1>业务线列表(字典)</h1>
  1.     <ul>
  1.         {% for row in v2 %}
  1.             <li>{{ row.id }}-{{ row.caption }}</li>
  1.         {% endfor %}
  1.     </ul>
  1.     <h1>业务线列表(元祖)</h1>
  1.     <ul>
  1.         {% for row in v3 %}
  1.             <li>{{ row.0 }}-{{ row.1 }}</li>
  1.         {% endfor %}
  1.     </ul>
  1. </body>
  1. </html>
2、函数
  1. from django.shortcuts import render
  1. from app01 import models
  1. # Create your views here.
 
  1. def business(request):
  1.     v1 = models.Business.objects.all()
  1.     #获取的是querySET,里面放的是对象,1个对象有1行数据,每个对象里有个id caption code
  1.     #[obj(id,caption,code),obj(id,caption,code)]
  1.     v2 = models.Business.objects.all().values('id','caption')
  1.     #querySET ,字典
  1.     #[{'id':1,'caption':'yunwei'},{}]
 
  1.     v3 = models.Business.objects.all().values_list('id','caption')
  1.     #querySET ,元祖
  1.     #[(1,运维部),(2,开发)]
 
  1.     return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
3、URL
  1. from django.conf.urls import url
  1. from django.contrib import admin
 
  1. from app01 import views
 
  1. urlpatterns = [
  1.     url(r'^admin/', admin.site.urls),
  1.     url(r'^business$', views.business),
  1. ]
4、models
  1. from django.db import models
 
  1. # Create your models here.
 
  1. #业务线
  1. class Business(models.Model):
  1.     #默认有个id列
  1.     caption = models.CharField(max_length=32)
  1.     code = models.CharField(max_length=32,null=True,default="SA")
 
  1. class Host(models.Model):
  1.     nid = models.AutoField(primary_key=True)
  1.     hostname = models.CharField(max_length=32,db_index=True)
  1.     ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
  1.     port = models.IntegerField()
  1.     b = models.ForeignKey(to="Business",to_field='id')
 
实现如下:
 
 
1对多跨表操作
 
上面上数据库取数据,可以拿到3种方式。
元素不一样而已。
对象的话: 封装到类,通过点去取值,因为对象字段要用点访问
字典:通过括号去取
元祖: 通过索引去取
 
 只要出现values内部元素都是字典,values_list内部都是元祖,其他的都是对象了。
 
querySET就是一个列表,来放很多对象,如果执行一个点get,ID=1,获取到的不是querySET了,而是一个对象,这个方法有个特殊的,如果ID=1不存在就直接爆出异常了。
怎么解决呢?只要是filter获取的都是querySET,如果没有拿到就是一个空列表。后面加 .first()
如果存在,获取到的就是对象,如果不存在,返归的就是none
 
 
现在业务表没有创建关系,下面搞个页面把主机列出来。
 
b 就是一个对象,封装了约束表的对象,所以通过b可以取出业务的信息,
b相当于另外一张表里面的一行数据
  1. print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id)
如果想要把业务表数据列出来,就可以通过b了
 
一般情况下,主机ID不需要显示,所以隐藏起来,因为我修改要使用到它,业务线ID也不要
 
具体操作:
1、HTML
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1. </head>
  1. <body>
  1.     <h1>host表</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>IP</th>
  1.                 <th>端口</th>
  1.                 <th>业务线名称</th>
 
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v1 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.ip }}</td>
  1.                     <td>{{ row.port }}</td>
  1.                     <td>{{ row.b.caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
  1. </body>
  1. </html>
2、函数
  1. def host(request):
  1.     #也有3种方式
  1.     v1 = models.Host.objects.filter(nid__gt=0)
  1.     for row in v1:
  1.         print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id)
 
  1.     # return HttpResponse("Host")
  1.     return render(request,'host.html',{'v1':v1})
3、URL
  1. from django.conf.urls import url
  1. from django.contrib import admin
 
  1. from app01 import views
 
  1. urlpatterns = [
  1.     url(r'^admin/', admin.site.urls),
  1.     url(r'^business$', views.business),
  1.     url(r'^host$', views.host),
  1. ]
4、models
  1. from django.db import models
 
  1. # Create your models here.
 
  1. #业务线
  1. class Business(models.Model):
  1.     #默认有个id列
  1.     caption = models.CharField(max_length=32)
  1.     code = models.CharField(max_length=32,null=True,default="SA")
 
  1. class Host(models.Model):
  1.     nid = models.AutoField(primary_key=True)
  1.     hostname = models.CharField(max_length=32,db_index=True)
  1.     ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
  1.     port = models.IntegerField()
  1.     b = models.ForeignKey(to="Business",to_field='id')
最后显示效果:
 
 
一对多表操作的三种方式
如果有外键,通过点来进行跨表
 
 
双下划线可以跨表,Django拿到双下划綫就会进行split,记住一点:
如果想跨表都是用双下划线。取值的时候就不一样了,因为拿到的是实实在在的对象,而下面取得都是字符串
 
 
最终实现:
 
 
代码如下:
1、URL
  1. from django.conf.urls import url
  1. from django.contrib import admin
 
  1. from app01 import views
 
  1. urlpatterns = [
  1.     url(r'^admin/', admin.site.urls),
  1.     url(r'^business$', views.business),
  1.     url(r'^host$', views.host),
  1. ]
 
2、函数
  1. def host(request):
  1.     #也有3种方式
  1.     v1 = models.Host.objects.filter(nid__gt=0)
  1.     # for row in v1:
  1.     #     print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id)
  1.     v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
  1.     # return HttpResponse("Host")
  1.     print(v2)
 
  1.     v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
  1.     # return HttpResponse("Host")
 
  1.     for row in v2:
  1.         print(row['nid'],row['hostname'],row['b_id'],row['b__caption'])
 
  1.     return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
 
3、models
  1. from django.db import models
 
  1. # Create your models here.
  1. # class Foo(models.Model):
  1. #     name = models.CharField(max_length=1)
 
 
  1. #业务线
  1. class Business(models.Model):
  1.     #默认有个id列
  1.     caption = models.CharField(max_length=32)
  1.     code = models.CharField(max_length=32,null=True,default="SA")
  1.     # fk = models.ForeignKey('Foo')
 
  1. class Host(models.Model):
  1.     nid = models.AutoField(primary_key=True)
  1.     hostname = models.CharField(max_length=32,db_index=True)
  1.     ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
  1.     port = models.IntegerField()
  1.     b = models.ForeignKey(to="Business",to_field='id')
 
4、host.html
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1. </head>
  1. <body>
  1.     <h1>host表(对象)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>IP</th>
  1.                 <th>端口</th>
  1.                 <th>业务线名称</th>
 
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v1 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.ip }}</td>
  1.                     <td>{{ row.port }}</td>
  1.                     <td>{{ row.b.caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(字典)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v2 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.b__caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(元祖)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v3 %}
  1.                 <tr  h-id="{{ row.0 }}" bid="{{ row.2 }}">
  1.                     <td>{{ row.1 }}</td>
  1.                     <td>{{ row.3 }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
  1. </body>
  1. </html>
 
增加1对多数据示例
 
position: fixed  absolute  relative
实现:
 
代码如下:
1、HTML,需要引入jQuery
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1.     <style>
  1.         .hide{
  1.             display: none;
  1.         }
  1.         .shade{
  1.             position: fixed;
  1.             top:0;
  1.             right:0;
  1.             left:0;
  1.             bottom:0;
  1.             background: black;
  1.             opacity:0.6;
  1.             z-index: 100;
  1.         }
  1.         .add-modal{
  1.             position: fixed;
  1.             height:300px;
  1.             width: 400px;
  1.             top: 100px;
  1.             left:50%;
  1.             z-index: 101;
  1.             border:1px solid red;
  1.             background: white;
  1.             margin-left: -200px;
  1.         }
  1.     </style>
  1. </head>
  1. <body>
  1.     <h1>host表(对象)</h1>
  1.     <div>
  1.         <input id="add_host" type="button" value="添加" />
  1.     </div>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>序号</th>
  1.                 <th>主机名</th>
  1.                 <th>IP</th>
  1.                 <th>端口</th>
  1.                 <th>业务线名称</th>
 
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v1 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ forloop.counter }}</td>
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.ip }}</td>
  1.                     <td>{{ row.port }}</td>
  1.                     <td>{{ row.b.caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(字典)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v2 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.b__caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(元祖)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v3 %}
  1.                 <tr  h-id="{{ row.0 }}" bid="{{ row.2 }}">
  1.                     <td>{{ row.1 }}</td>
  1.                     <td>{{ row.3 }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     #遮罩层
  1.     <div class="shade hide"></div>
 
  1.     #添加层
  1.     <div class="add-modal hide">
  1.         <form method="POST" action="/host">
  1.             <div class="group">
  1.                 <input type="text" placeholder="主机名" name="hostname" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input type="text" placeholder="IP" name="ip" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input type="text" placeholder="端口 " name="port" />
  1.             </div>
 
  1.              <div class="group">
  1.                  <select name="b_id">
  1.                      {% for op in b_list %}
  1.                      <option value="{{ op.id }}">{{ op.caption }}</option>
  1.                      {% endfor %}
  1.                  </select>
  1.             </div>
 
  1.             <input type="submit" value="提交">
  1.             <input id="cancel" type="button" value="取消">
  1.         </form>
  1.     </div>
  1.     <script src="/static/jquery-1.12.4.js"></script>
  1.     <script>
  1.         $(function(){
  1.             $('#add_host').click(function(){
  1.                 $('.shade,.add-modal').removeClass('hide');
  1.             })
 
  1.             $('#cancel').click(function(){
  1.                 $('.shade,.add-modal').addClass('hide');
  1.             })
  1.         })
  1.     </script>
  1. </body>
  1. </html>
2、函数
  1. def host(request):
  1.     if request.method == 'GET':
  1.         v1 = models.Host.objects.filter(nid__gt=0)
  1.         v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
  1.         v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
 
  1.         b_list = models.Business.objects.all()
 
  1.         return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
 
  1.     elif  request.method == "POST":
  1.         h = request.POST.get("hostname")
  1.         i = request.POST.get("ip")
  1.         p = request.POST.get("port")
  1.         b = request.POST.get("b_id")
  1.         # models.Host.objects.create(hostname=h,
  1.         #                            ip=i,
  1.         #                            port=p,
  1.         #                            b=models.Business.objects.get(id=b)
  1.         #                            )
  1.         models.Host.objects.create(hostname=h,
  1.                                    ip=i,
  1.                                    port=p,
  1.                                    b_id=b
  1.                                    )
  1.         return redirect('/host')
 
3、URL
  1. from django.conf.urls import url
  1. from django.contrib import admin
 
  1. from app01 import views
 
  1. urlpatterns = [
  1.     url(r'^admin/', admin.site.urls),
  1.     url(r'^business$', views.business),
  1.     url(r'^host$', views.host),
  1. ]
 
4、models 
同上
 
初识ajax ,加入提示
上面的会出现,提交的时候出现空值,这个是不允许的,如何解决呢?
通过新URL的方式可以解决,但是如果有弹框呢?我点击提交对话框都不在了额,那我错误提示放哪呢?
SO,搞一个按钮,让他悄悄提交,提交数据到后台,但是页面不刷新,后台拿到在给他一个回复
 
这里就用Ajax来提交。
好多地方都在使用,比如说下面的
 
就是用jQuery来发一个Ajax请求,
$.ajax({
url: '/host',
  • type: "POST",
  • data: {'k1':"123",'k2':"root"},
  • success: function(data){
  • }
  • })
 
实现如下:
 
具体实现:
1、HTML
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1.     <style>
  1.         .hide{
  1.             display: none;
  1.         }
  1.         .shade{
  1.             position: fixed;
  1.             top:0;
  1.             right:0;
  1.             left:0;
  1.             bottom:0;
  1.             background: black;
  1.             opacity:0.6;
  1.             z-index: 100;
  1.         }
  1.         .add-modal{
  1.             position: fixed;
  1.             height:300px;
  1.             width: 400px;
  1.             top: 100px;
  1.             left:50%;
  1.             z-index: 101;
  1.             border:1px solid red;
  1.             background: white;
  1.             margin-left: -200px;
  1.         }
  1.     </style>
  1. </head>
  1. <body>
  1.     <h1>host表(对象)</h1>
  1.     <div>
  1.         <input id="add_host" type="button" value="添加" />
  1.     </div>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>序号</th>
  1.                 <th>主机名</th>
  1.                 <th>IP</th>
  1.                 <th>端口</th>
  1.                 <th>业务线名称</th>
 
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v1 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ forloop.counter }}</td>
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.ip }}</td>
  1.                     <td>{{ row.port }}</td>
  1.                     <td>{{ row.b.caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(字典)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v2 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.b__caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(元祖)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v3 %}
  1.                 <tr  h-id="{{ row.0 }}" bid="{{ row.2 }}">
  1.                     <td>{{ row.1 }}</td>
  1.                     <td>{{ row.3 }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     #遮罩层
  1.     <div class="shade hide"></div>
 
  1.     #添加层
  1.     <div class="add-modal hide">
  1.         <form method="POST" action="/host">
  1.             <div class="group">
  1.                 <input id="host" type="text" placeholder="主机名" name="hostname" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input id="ip" type="text" placeholder="IP" name="ip" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input id="port" type="text" placeholder="端口 " name="port" />
  1.             </div>
 
  1.              <div class="group">
  1.                  <select id="sel" name="b_id">
  1.                      {% for op in b_list %}
  1.                      <option value="{{ op.id }}">{{ op.caption }}</option>
  1.                      {% endfor %}
  1.                  </select>
  1.             </div>
 
  1.             <input type="submit" value="提交">
  1.             <a id="ajax_submit" style="display: inline-block;padding: 5px;color: white">提交Ajax</a>
  1.             <input id="cancel" type="button" value="取消">
  1.         </form>
  1.     </div>
  1.     <script src="/static/jquery-1.12.4.js"></script>
  1.     <script>
  1.         $(function(){
  1.             $('#add_host').click(function(){
  1.                 $('.shade,.add-modal').removeClass('hide');
  1.             });
 
  1.             $('#cancel').click(function(){
  1.                 $('.shade,.add-modal').addClass('hide');
  1.             });
 
  1.             $('#ajax_submit').click(function(){
  1.                 $.ajax({
  1.                     url: "/test_ajax",
  1.                     type: 'POST',
  1.                     data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
  1.                     success: function(data){
  1.                         if(data == "OK"){
  1.                             location.reload()
  1.                         }else{
  1.                           alert(data);
  1.                         }
 
  1.                     }
  1.                 })
  1.             })
  1.         })
  1.     </script>
  1. </body>
  1. </html>
 
2、函数
  1. def test_ajax(request):
  1.     # print(request.method,request.POST,sep='\t')
  1.     # import time
  1.     # time.sleep(5)
 
  1.     h = request.POST.get("hostname")
  1.     i = request.POST.get("ip")
  1.     p = request.POST.get("port")
  1.     b = request.POST.get("b_id")
  1.     if h and len(h) >5:
 
 
  1.         models.Host.objects.create(hostname=h,
  1.                                        ip=i,
  1.                                        port=p,
  1.                                        b_id=b
  1.                                    )
  1.         return HttpResponse('OK')
  1.     else:
  1.         return HttpResponse('太短了')
 
3、URL
  1. from app01 import views
 
  1. urlpatterns = [
  1.     url(r'^admin/', admin.site.urls),
  1.     url(r'^business$', views.business),
  1.     url(r'^host$', views.host),
  1.     url(r'^test_ajax$', views.test_ajax),
  1. ]
 
4、models
同上
 
 
Ajax的整理:
 
 
 
继续更改
会用到下面内容
 
 
 
 
 
修改HTML
 
  1.         <input type="submit" value="提交">
  1.         <a id="ajax_submit" style="display: inline-block;padding: 5px;background-color: red;color: white">提交Ajax</a>
  1.         <input id="cancel" type="button" value="取消">
  1.         <span id="erro_msg" style="color: red;"></span>
  1.     </form>
  1. </div>
  1. <script src="/static/jquery-1.12.4.js"></script>
  1. <script>
  1.     $(function(){
  1.         $('#add_host').click(function(){
  1.             $('.shade,.add-modal').removeClass('hide');
  1.         });
 
  1.         $('#cancel').click(function(){
  1.             $('.shade,.add-modal').addClass('hide');
  1.         });
 
  1.         $('#ajax_submit').click(function(){
  1.             $.ajax({
  1.                 url: "/test_ajax",
  1.                 type: 'POST',
  1.                 data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
  1.                 success: function(data){
  1.                     var obj = JSON.parse(data);
  1.                     if(obj.status){
  1.                         location.reload();
  1.                     }else{
  1.                         $('#erro_msg').text(obj.error);
  1.                     }
 
  1.                 }
  1.             })
  1.         })
  1.     })
  1. </script>
修改函数
  1. def test_ajax(request):
  1.     # print(request.method,request.POST,sep='\t')
  1.     # import time
  1.     # time.sleep(5)
  1.     import json
  1.     ret = {'status': True,'error':None,'data':None}
  1.     try:
  1.         h = request.POST.get("hostname")
  1.         i = request.POST.get("ip")
  1.         p = request.POST.get("port")
  1.         b = request.POST.get("b_id")
  1.         if h and len(h) >5:
  1.             models.Host.objects.create(hostname=h,
  1.                                            ip=i,
  1.                                            port=p,
  1.                                            b_id=b)
  1.         #     return HttpResponse('OK')
  1.         else:
  1.             ret['status'] = False
  1.             ret['error'] = "太短了"
  1.             # return HttpResponse('太短了')
  1.     except Exception as e:
  1.         ret['status'] = False
  1.         ret['error'] = "请求错误"
  1.     return HttpResponse(json.dumps(ret))
 
建议:
永远让服务端返回一个字典。
return HttpResponse(json.dumps(字典))
 
删除类似:
出来一个弹框,把ID=某行删除掉。form表单可以,ajax也可以,或者找到当前标签,remove掉就不需要刷新了。
 
编辑类似:
 
通过ID去取值。
 
 
 
如果发送ajax请求
  1. data: $('#edit_form').serialize()
这个会把form表单值打包发送到后台
 
效果取值:
HTML代码
  1. <!DOCTYPE html>
  1. <html lang="en">
  1. <head>
  1.     <meta charset="UTF-8">
  1.     <title>Title</title>
  1.     <style>
  1.         .hide{
  1.             display: none;
  1.         }
  1.         .shade{
  1.             position: fixed;
  1.             top:0;
  1.             right:0;
  1.             left:0;
  1.             bottom:0;
  1.             background: black;
  1.             opacity:0.6;
  1.             z-index: 100;
  1.         }
  1.         .add-modal,.edit-modal{
  1.             position: fixed;
  1.             height:300px;
  1.             width: 400px;
  1.             top: 100px;
  1.             left:50%;
  1.             z-index: 101;
  1.             border:1px solid red;
  1.             background: white;
  1.             margin-left: -200px;
  1.         }
  1.     </style>
  1. </head>
  1. <body>
  1.     <h1>host表(对象)</h1>
  1.     <div>
  1.         <input id="add_host" type="button" value="添加" />
  1.     </div>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>序号</th>
  1.                 <th>主机名</th>
  1.                 <th>IP</th>
  1.                 <th>端口</th>
  1.                 <th>业务线名称</th>
  1.                 <th>操作</th>
 
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v1 %}
  1.                 <tr  hid="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ forloop.counter }}</td>
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.ip }}</td>
  1.                     <td>{{ row.port }}</td>
  1.                     <td>{{ row.b.caption }}</td>
  1.                     <td>
  1.                         <a class="edit">编辑</a>|<a class="delete">删除</a>
  1.                     </td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(字典)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v2 %}
  1.                 <tr  h-id="{{ row.nid }}" bid="{{ row.b_id }}">
  1.                     <td>{{ row.hostname }}</td>
  1.                     <td>{{ row.b__caption }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     <h1>host表(元祖)</h1>
  1.     <table border="1">
  1.         <thead>
  1.             <tr>
  1.                 <th>主机名</th>
  1.                 <th>业务线名称</th>
  1.             </tr>
  1.         </thead>
  1.         <tbody>
  1.             {% for row in v3 %}
  1.                 <tr  h-id="{{ row.0 }}" bid="{{ row.2 }}">
  1.                     <td>{{ row.1 }}</td>
  1.                     <td>{{ row.3 }}</td>
  1.                 </tr>
  1.             {% endfor  %}
  1.         </tbody>
  1.     </table>
 
  1.     #遮罩层
  1.     <div class="shade hide"></div>
 
  1.     #添加层
  1.     <div class="add-modal hide">
  1.         <form id="add_form" method="POST" action="/host">
  1.             <div class="group">
  1.                 <input id="host" type="text" placeholder="主机名" name="hostname" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input id="ip" type="text" placeholder="IP" name="ip" />
  1.             </div>
 
  1.              <div class="group">
  1.                 <input id="port" type="text" placeholder="端口 " name="port" />
  1.             </div>
 
  1.              <div class="group">
  1.                  <select id="sel" name="b_id">
  1.                      {% for op in b_list %}
  1.                      <option value="{{ op.id }}">{{ op.caption }}</option>
  1.                      {% endfor %}
  1.                  </select>
  1.             </div>
 
  1.             <input type="submit" value="提交">
  1.             <a id="ajax_submit" style="display: inline-block;padding: 5px;color: white">提交Ajax</a>
  1.             <input id="cancel" type="button" value="取消">
  1.             <span id="erro_msg" style="color: red;"></span>
  1.         </form>
  1.     </div>
 
  1.     <div class="edit-modal hide">
  1.         <form id="edit_form" method="POST" action="/host">
  1.                 <input type="text" name="nid" style="display: none;">
  1.                 <input  type="text" placeholder="主机名" name="hostname" />
  1.                 <input  type="text" placeholder="IP" name="ip" />
  1.                 <input  type="text" placeholder="端口 " name="port" />
  1.                  <select name="b_id">
  1.                      {% for op in b_list %}
  1.                      <option value="{{ op.id }}">{{ op.caption }}</option>
  1.                      {% endfor %}
  1.                  </select>
  1.             <a id="ajax_submit_edit">确定编辑</a>
 
  1.         </form>
  1.     </div>
 
 
  1.     <script src="/static/jquery-1.12.4.js"></script>
  1.     <script>
  1.         $(function(){
  1.             $('#add_host').click(function(){
  1.                 $('.shade,.add-modal').removeClass('hide');
  1.             });
 
  1.             $('#cancel').click(function(){
  1.                 $('.shade,.add-modal').addClass('hide');
  1.             });
 
  1.             $('#ajax_submit').click(function(){
  1.                 $.ajax({
  1.                     url: "/test_ajax",
  1.                     type: 'POST',
  1. {#                    data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},#}
  1.                     data: $('#add_form').serialize(),
  1.                     success: function(data){
  1.                         var obj = JSON.parse(data);
  1.                         if(obj.status){
  1.                             location.reload();
  1.                         }else{
  1.                             $('#erro_msg').text(obj.error);
  1.                         }
  1.                     }
  1.                 })
  1.             })
 
  1.             $('.edit').click(function(){
  1.                 $('.shade,.edit-modal').removeClass('hide');
 
  1.                 var bid = $(this).parent().parent().attr('bid');
  1.                 var nid = $(this).parent().parent().attr('hid');
 
  1.                 $('#edit_form').find('select').val(bid);
  1.                 $('#edit_form').find('input[name="nid"]').val(nid);
 
  1.                 //修改操作了
  1.                 $.ajax({
  1.                     data: $('#edit_form').serialize()
  1.                 });
  1.                 //获取到models.Host.objects.filter(nid=nid).update()
  1.             })
  1.         })
  1.     </script>
  1. </body>
  1. </html>
里面涉及的知识点:
1、拿到NID并隐藏,用于提交数据
2、使用ajax来提交数据
 
posted @ 2017-03-22 16:05  我还可以试试  阅读(448)  评论(0编辑  收藏  举报