一個初學者的辛酸路程-依舊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來提交數據
相關文章
相關標籤/搜索