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

回顾:

一、Django的请求声明周期?
 
请求过来,先到URL,URL这里写了一大堆路由关系映射,若是匹配成功,执行对应的函数,或者执行类里面对应的方法,FBV和CBV,本质上返回的内容都是字符串,经过复杂字符串来讲比较麻烦,就写到文件里面,经过OPEN函数打开再返回给用户,因此模板能够任何文件名。
后台必定要说,模板里面有特殊的标记,待特殊标记的模板+值进行渲染,获得最终给用户的字符串。
总结为:
路由系统==》视图函数==》获取模板+数据==>渲染==》最终字符串返回给用户。
 
二、路由系统
有哪几种对应?
一、URL对应函数,能够包含正则
/index/    ==>  函数(参数)或者类 .as_view() (参数)
二、上面是定时的,因此有正则
/detail/(\d+)  ==> 函数(参数)或类  .as_vies() (参数)
三、基于问号和参数名
/detail/(?P<nid>\d+)  ==> 函数(参数)或类  .as_vies() (参数)
四、路由的分发,使用include和前缀来区分
/detail/ ==> include("app01.urls")
五、规定路由对应的名字
/detail/   name="a1"   ==> include("app01.urls")
  • 视图中: 使用reverse函数来作
  • 模板种: {% url  "a1" %}
三、视图函数
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(字符串)
四、模板语言
  • 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>
 
五、数据库取数据  ORM(关系对象映射,写的类自动转为SQL语句取数据,去到之后转换成对象给我)
两个操做:
一、建立类和字段
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,否则会出问题,数据库建立不了。
 
二、操做
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对多表结构
执行建立表命令,出现下面报错
 
文件在于没有注册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")
 
具体操做:
一、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>
二、函数
  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})
三、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. ]
四、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也不要
 
具体操做:
一、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>
二、函数
  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})
三、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. ]
四、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,记住一点:
若是想跨表都是用双下划线。取值的时候就不同了,由于拿到的是实实在在的对象,而下面取得都是字符串
 
 
最终实现:
 
 
代码以下:
一、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. ]
 
二、函数
  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})
 
三、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')
 
四、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
实现:
 
代码以下:
一、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>
二、函数
  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')
 
三、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. ]
 
四、models 
同上
 
初识ajax ,加入提示
上面的会出现,提交的时候出现空值,这个是不容许的,如何解决呢?
经过新URL的方式能够解决,可是若是有弹框呢?我点击提交对话框都不在了额,那我错误提示放哪呢?
SO,搞一个按钮,让他悄悄提交,提交数据到后台,可是页面不刷新,后台拿到在给他一个回复
 
这里就用Ajax来提交。
好多地方都在使用,好比说下面的
 
就是用jQuery来发一个Ajax请求,
$.ajax({
url: '/host',
  • type: "POST",
  • data: {'k1':"123",'k2':"root"},
  • success: function(data){
  • }
  • })
 
实现以下:
 
具体实现:
一、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>
 
二、函数
  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('过短了')
 
三、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. ]
 
四、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>
里面涉及的知识点:
一、拿到NID并隐藏,用于提交数据
二、使用ajax来提交数据
相关文章
相关标签/搜索