回顾:
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
创建表,表信息如下:
- from django.db import models
- # Create your models here.
- #业务线
- class Business(models.Model):
- #默认有个id列
- caption = models.CharField(max_length=32)
- class Host(models.Model):
- nid = models.AutoField(primary_key=True)
- hostname = models.CharField(max_length=32,db_index=True)
- ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
- port = models.IntegerField()
- b = models.ForeignKey(to="Business",to_field='id')
执行下面命令创建表结构
如果我创建完了以后呢,然后我又加了一条语句,会报错呢?
执行下面命令,会有2种选择,
所以可以修改为这个
- code = models.CharField(max_length=32,null=True,default="SA")
具体操作:
1、HTML
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <h1>业务线列表(对象方式)</h1>
- <ul>
- {% for row in v1 %}
- <li>{{ row.id }}-{{ row.caption }}-{{ row.code }}</li>
- {% endfor %}
- </ul>
- <h1>业务线列表(字典)</h1>
- <ul>
- {% for row in v2 %}
- <li>{{ row.id }}-{{ row.caption }}</li>
- {% endfor %}
- </ul>
- <h1>业务线列表(元祖)</h1>
- <ul>
- {% for row in v3 %}
- <li>{{ row.0 }}-{{ row.1 }}</li>
- {% endfor %}
- </ul>
- </body>
- </html>
2、函数
- from django.shortcuts import render
- from app01 import models
- # Create your views here.
- def business(request):
- v1 = models.Business.objects.all()
- #获取的是querySET,里面放的是对象,1个对象有1行数据,每个对象里有个id caption code
- #[obj(id,caption,code),obj(id,caption,code)]
- v2 = models.Business.objects.all().values('id','caption')
- #querySET ,字典
- #[{'id':1,'caption':'yunwei'},{}]
- v3 = models.Business.objects.all().values_list('id','caption')
- #querySET ,元祖
- #[(1,运维部),(2,开发)]
- return render(request,'business.html',{'v1':v1,'v2':v2,'v3':v3})
3、URL
- from django.conf.urls import url
- from django.contrib import admin
- from app01 import views
- urlpatterns = [
- url(r'^admin/', admin.site.urls),
- url(r'^business$', views.business),
- ]
4、models
- from django.db import models
- # Create your models here.
- #业务线
- class Business(models.Model):
- #默认有个id列
- caption = models.CharField(max_length=32)
- code = models.CharField(max_length=32,null=True,default="SA")
- class Host(models.Model):
- nid = models.AutoField(primary_key=True)
- hostname = models.CharField(max_length=32,db_index=True)
- ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
- port = models.IntegerField()
- b = models.ForeignKey(to="Business",to_field='id')
实现如下:
1对多跨表操作
上面上数据库取数据,可以拿到3种方式。
元素不一样而已。
对象的话: 封装到类,通过点去取值,因为对象字段要用点访问
字典:通过括号去取
元祖: 通过索引去取
只要出现values内部元素都是字典,values_list内部都是元祖,其他的都是对象了。
querySET就是一个列表,来放很多对象,如果执行一个点get,ID=1,获取到的不是querySET了,而是一个对象,这个方法有个特殊的,如果ID=1不存在就直接爆出异常了。
怎么解决呢?只要是filter获取的都是querySET,如果没有拿到就是一个空列表。后面加 .first()
如果存在,获取到的就是对象,如果不存在,返归的就是none
现在业务表没有创建关系,下面搞个页面把主机列出来。
b 就是一个对象,封装了约束表的对象,所以通过b可以取出业务的信息,
b相当于另外一张表里面的一行数据
- 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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <h1>host表</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>IP</th>
- <th>端口</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v1 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.ip }}</td>
- <td>{{ row.port }}</td>
- <td>{{ row.b.caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- </body>
- </html>
2、函数
- def host(request):
- #也有3种方式
- v1 = models.Host.objects.filter(nid__gt=0)
- for row in v1:
- print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id)
- # return HttpResponse("Host")
- return render(request,'host.html',{'v1':v1})
3、URL
- from django.conf.urls import url
- from django.contrib import admin
- from app01 import views
- urlpatterns = [
- url(r'^admin/', admin.site.urls),
- url(r'^business$', views.business),
- url(r'^host$', views.host),
- ]
4、models
- from django.db import models
- # Create your models here.
- #业务线
- class Business(models.Model):
- #默认有个id列
- caption = models.CharField(max_length=32)
- code = models.CharField(max_length=32,null=True,default="SA")
- class Host(models.Model):
- nid = models.AutoField(primary_key=True)
- hostname = models.CharField(max_length=32,db_index=True)
- ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
- port = models.IntegerField()
- b = models.ForeignKey(to="Business",to_field='id')
最后显示效果:
一对多表操作的三种方式
如果有外键,通过点来进行跨表
双下划线可以跨表,Django拿到双下划綫就会进行split,记住一点:
如果想跨表都是用双下划线。取值的时候就不一样了,因为拿到的是实实在在的对象,而下面取得都是字符串
最终实现:
代码如下:
1、URL
- from django.conf.urls import url
- from django.contrib import admin
- from app01 import views
- urlpatterns = [
- url(r'^admin/', admin.site.urls),
- url(r'^business$', views.business),
- url(r'^host$', views.host),
- ]
2、函数
- def host(request):
- #也有3种方式
- v1 = models.Host.objects.filter(nid__gt=0)
- # for row in v1:
- # print(row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code,row.b.id)
- v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
- # return HttpResponse("Host")
- print(v2)
- v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
- # return HttpResponse("Host")
- for row in v2:
- print(row['nid'],row['hostname'],row['b_id'],row['b__caption'])
- return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3})
3、models
- from django.db import models
- # Create your models here.
- # class Foo(models.Model):
- # name = models.CharField(max_length=1)
- #业务线
- class Business(models.Model):
- #默认有个id列
- caption = models.CharField(max_length=32)
- code = models.CharField(max_length=32,null=True,default="SA")
- # fk = models.ForeignKey('Foo')
- class Host(models.Model):
- nid = models.AutoField(primary_key=True)
- hostname = models.CharField(max_length=32,db_index=True)
- ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
- port = models.IntegerField()
- b = models.ForeignKey(to="Business",to_field='id')
4、host.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <h1>host表(对象)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>IP</th>
- <th>端口</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v1 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.ip }}</td>
- <td>{{ row.port }}</td>
- <td>{{ row.b.caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(字典)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v2 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.b__caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(元祖)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v3 %}
- <tr h-id="{{ row.0 }}" bid="{{ row.2 }}">
- <td>{{ row.1 }}</td>
- <td>{{ row.3 }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- </body>
- </html>
增加1对多数据示例
position: fixed absolute relative
实现:
代码如下:
1、HTML,需要引入jQuery
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <style>
- .hide{
- display: none;
- }
- .shade{
- position: fixed;
- top:0;
- right:0;
- left:0;
- bottom:0;
- background: black;
- opacity:0.6;
- z-index: 100;
- }
- .add-modal{
- position: fixed;
- height:300px;
- width: 400px;
- top: 100px;
- left:50%;
- z-index: 101;
- border:1px solid red;
- background: white;
- margin-left: -200px;
- }
- </style>
- </head>
- <body>
- <h1>host表(对象)</h1>
- <div>
- <input id="add_host" type="button" value="添加" />
- </div>
- <table border="1">
- <thead>
- <tr>
- <th>序号</th>
- <th>主机名</th>
- <th>IP</th>
- <th>端口</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v1 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ forloop.counter }}</td>
- <td>{{ row.hostname }}</td>
- <td>{{ row.ip }}</td>
- <td>{{ row.port }}</td>
- <td>{{ row.b.caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(字典)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v2 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.b__caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(元祖)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v3 %}
- <tr h-id="{{ row.0 }}" bid="{{ row.2 }}">
- <td>{{ row.1 }}</td>
- <td>{{ row.3 }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- #遮罩层
- <div class="shade hide"></div>
- #添加层
- <div class="add-modal hide">
- <form method="POST" action="/host">
- <div class="group">
- <input type="text" placeholder="主机名" name="hostname" />
- </div>
- <div class="group">
- <input type="text" placeholder="IP" name="ip" />
- </div>
- <div class="group">
- <input type="text" placeholder="端口 " name="port" />
- </div>
- <div class="group">
- <select name="b_id">
- {% for op in b_list %}
- <option value="{{ op.id }}">{{ op.caption }}</option>
- {% endfor %}
- </select>
- </div>
- <input type="submit" value="提交">
- <input id="cancel" type="button" value="取消">
- </form>
- </div>
- <script src="/static/jquery-1.12.4.js"></script>
- <script>
- $(function(){
- $('#add_host').click(function(){
- $('.shade,.add-modal').removeClass('hide');
- })
- $('#cancel').click(function(){
- $('.shade,.add-modal').addClass('hide');
- })
- })
- </script>
- </body>
- </html>
2、函数
- def host(request):
- if request.method == 'GET':
- v1 = models.Host.objects.filter(nid__gt=0)
- v2 = models.Host.objects.filter(nid__gt=0).values('nid','hostname','b_id','b__caption')
- v3 = models.Host.objects.filter(nid__gt=0).values_list('nid','hostname','b_id','b__caption')
- b_list = models.Business.objects.all()
- return render(request,'host.html',{'v1':v1,'v2':v2,'v3':v3,'b_list':b_list})
- elif request.method == "POST":
- h = request.POST.get("hostname")
- i = request.POST.get("ip")
- p = request.POST.get("port")
- b = request.POST.get("b_id")
- # models.Host.objects.create(hostname=h,
- # ip=i,
- # port=p,
- # b=models.Business.objects.get(id=b)
- # )
- models.Host.objects.create(hostname=h,
- ip=i,
- port=p,
- b_id=b
- )
- return redirect('/host')
3、URL
- from django.conf.urls import url
- from django.contrib import admin
- from app01 import views
- urlpatterns = [
- url(r'^admin/', admin.site.urls),
- url(r'^business$', views.business),
- url(r'^host$', views.host),
- ]
4、models
同上
初识ajax ,加入提示
上面的会出现,提交的时候出现空值,这个是不允许的,如何解决呢?
通过新URL的方式可以解决,但是如果有弹框呢?我点击提交对话框都不在了额,那我错误提示放哪呢?
SO,搞一个按钮,让他悄悄提交,提交数据到后台,但是页面不刷新,后台拿到在给他一个回复
这里就用Ajax来提交。
好多地方都在使用,比如说下面的
就是用jQuery来发一个Ajax请求,
$.ajax({
url: '/host',
- type: "POST",
- data: {'k1':"123",'k2':"root"},
- success: function(data){
- }
- })
实现如下:
具体实现:
1、HTML
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <style>
- .hide{
- display: none;
- }
- .shade{
- position: fixed;
- top:0;
- right:0;
- left:0;
- bottom:0;
- background: black;
- opacity:0.6;
- z-index: 100;
- }
- .add-modal{
- position: fixed;
- height:300px;
- width: 400px;
- top: 100px;
- left:50%;
- z-index: 101;
- border:1px solid red;
- background: white;
- margin-left: -200px;
- }
- </style>
- </head>
- <body>
- <h1>host表(对象)</h1>
- <div>
- <input id="add_host" type="button" value="添加" />
- </div>
- <table border="1">
- <thead>
- <tr>
- <th>序号</th>
- <th>主机名</th>
- <th>IP</th>
- <th>端口</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v1 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ forloop.counter }}</td>
- <td>{{ row.hostname }}</td>
- <td>{{ row.ip }}</td>
- <td>{{ row.port }}</td>
- <td>{{ row.b.caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(字典)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v2 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.b__caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(元祖)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v3 %}
- <tr h-id="{{ row.0 }}" bid="{{ row.2 }}">
- <td>{{ row.1 }}</td>
- <td>{{ row.3 }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- #遮罩层
- <div class="shade hide"></div>
- #添加层
- <div class="add-modal hide">
- <form method="POST" action="/host">
- <div class="group">
- <input id="host" type="text" placeholder="主机名" name="hostname" />
- </div>
- <div class="group">
- <input id="ip" type="text" placeholder="IP" name="ip" />
- </div>
- <div class="group">
- <input id="port" type="text" placeholder="端口 " name="port" />
- </div>
- <div class="group">
- <select id="sel" name="b_id">
- {% for op in b_list %}
- <option value="{{ op.id }}">{{ op.caption }}</option>
- {% endfor %}
- </select>
- </div>
- <input type="submit" value="提交">
- <a id="ajax_submit" style="display: inline-block;padding: 5px;color: white">提交Ajax</a>
- <input id="cancel" type="button" value="取消">
- </form>
- </div>
- <script src="/static/jquery-1.12.4.js"></script>
- <script>
- $(function(){
- $('#add_host').click(function(){
- $('.shade,.add-modal').removeClass('hide');
- });
- $('#cancel').click(function(){
- $('.shade,.add-modal').addClass('hide');
- });
- $('#ajax_submit').click(function(){
- $.ajax({
- url: "/test_ajax",
- type: 'POST',
- data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
- success: function(data){
- if(data == "OK"){
- location.reload()
- }else{
- alert(data);
- }
- }
- })
- })
- })
- </script>
- </body>
- </html>
2、函数
- def test_ajax(request):
- # print(request.method,request.POST,sep='\t')
- # import time
- # time.sleep(5)
- h = request.POST.get("hostname")
- i = request.POST.get("ip")
- p = request.POST.get("port")
- b = request.POST.get("b_id")
- if h and len(h) >5:
- models.Host.objects.create(hostname=h,
- ip=i,
- port=p,
- b_id=b
- )
- return HttpResponse('OK')
- else:
- return HttpResponse('太短了')
3、URL
- from app01 import views
- urlpatterns = [
- url(r'^admin/', admin.site.urls),
- url(r'^business$', views.business),
- url(r'^host$', views.host),
- url(r'^test_ajax$', views.test_ajax),
- ]
4、models
同上
Ajax的整理:
继续更改
会用到下面内容
修改HTML
- <input type="submit" value="提交">
- <a id="ajax_submit" style="display: inline-block;padding: 5px;background-color: red;color: white">提交Ajax</a>
- <input id="cancel" type="button" value="取消">
- <span id="erro_msg" style="color: red;"></span>
- </form>
- </div>
- <script src="/static/jquery-1.12.4.js"></script>
- <script>
- $(function(){
- $('#add_host').click(function(){
- $('.shade,.add-modal').removeClass('hide');
- });
- $('#cancel').click(function(){
- $('.shade,.add-modal').addClass('hide');
- });
- $('#ajax_submit').click(function(){
- $.ajax({
- url: "/test_ajax",
- type: 'POST',
- data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},
- success: function(data){
- var obj = JSON.parse(data);
- if(obj.status){
- location.reload();
- }else{
- $('#erro_msg').text(obj.error);
- }
- }
- })
- })
- })
- </script>
修改函数
- def test_ajax(request):
- # print(request.method,request.POST,sep='\t')
- # import time
- # time.sleep(5)
- import json
- ret = {'status': True,'error':None,'data':None}
- try:
- h = request.POST.get("hostname")
- i = request.POST.get("ip")
- p = request.POST.get("port")
- b = request.POST.get("b_id")
- if h and len(h) >5:
- models.Host.objects.create(hostname=h,
- ip=i,
- port=p,
- b_id=b)
- # return HttpResponse('OK')
- else:
- ret['status'] = False
- ret['error'] = "太短了"
- # return HttpResponse('太短了')
- except Exception as e:
- ret['status'] = False
- ret['error'] = "请求错误"
- return HttpResponse(json.dumps(ret))
建议:
永远让服务端返回一个字典。
return HttpResponse(json.dumps(字典))
删除类似:
出来一个弹框,把ID=某行删除掉。form表单可以,ajax也可以,或者找到当前标签,remove掉就不需要刷新了。
编辑类似:
通过ID去取值。
如果发送ajax请求
- data: $('#edit_form').serialize()
这个会把form表单值打包发送到后台
效果取值:
HTML代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <style>
- .hide{
- display: none;
- }
- .shade{
- position: fixed;
- top:0;
- right:0;
- left:0;
- bottom:0;
- background: black;
- opacity:0.6;
- z-index: 100;
- }
- .add-modal,.edit-modal{
- position: fixed;
- height:300px;
- width: 400px;
- top: 100px;
- left:50%;
- z-index: 101;
- border:1px solid red;
- background: white;
- margin-left: -200px;
- }
- </style>
- </head>
- <body>
- <h1>host表(对象)</h1>
- <div>
- <input id="add_host" type="button" value="添加" />
- </div>
- <table border="1">
- <thead>
- <tr>
- <th>序号</th>
- <th>主机名</th>
- <th>IP</th>
- <th>端口</th>
- <th>业务线名称</th>
- <th>操作</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v1 %}
- <tr hid="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ forloop.counter }}</td>
- <td>{{ row.hostname }}</td>
- <td>{{ row.ip }}</td>
- <td>{{ row.port }}</td>
- <td>{{ row.b.caption }}</td>
- <td>
- <a class="edit">编辑</a>|<a class="delete">删除</a>
- </td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(字典)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v2 %}
- <tr h-id="{{ row.nid }}" bid="{{ row.b_id }}">
- <td>{{ row.hostname }}</td>
- <td>{{ row.b__caption }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- <h1>host表(元祖)</h1>
- <table border="1">
- <thead>
- <tr>
- <th>主机名</th>
- <th>业务线名称</th>
- </tr>
- </thead>
- <tbody>
- {% for row in v3 %}
- <tr h-id="{{ row.0 }}" bid="{{ row.2 }}">
- <td>{{ row.1 }}</td>
- <td>{{ row.3 }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
- #遮罩层
- <div class="shade hide"></div>
- #添加层
- <div class="add-modal hide">
- <form id="add_form" method="POST" action="/host">
- <div class="group">
- <input id="host" type="text" placeholder="主机名" name="hostname" />
- </div>
- <div class="group">
- <input id="ip" type="text" placeholder="IP" name="ip" />
- </div>
- <div class="group">
- <input id="port" type="text" placeholder="端口 " name="port" />
- </div>
- <div class="group">
- <select id="sel" name="b_id">
- {% for op in b_list %}
- <option value="{{ op.id }}">{{ op.caption }}</option>
- {% endfor %}
- </select>
- </div>
- <input type="submit" value="提交">
- <a id="ajax_submit" style="display: inline-block;padding: 5px;color: white">提交Ajax</a>
- <input id="cancel" type="button" value="取消">
- <span id="erro_msg" style="color: red;"></span>
- </form>
- </div>
- <div class="edit-modal hide">
- <form id="edit_form" method="POST" action="/host">
- <input type="text" name="nid" style="display: none;">
- <input type="text" placeholder="主机名" name="hostname" />
- <input type="text" placeholder="IP" name="ip" />
- <input type="text" placeholder="端口 " name="port" />
- <select name="b_id">
- {% for op in b_list %}
- <option value="{{ op.id }}">{{ op.caption }}</option>
- {% endfor %}
- </select>
- <a id="ajax_submit_edit">确定编辑</a>
- </form>
- </div>
- <script src="/static/jquery-1.12.4.js"></script>
- <script>
- $(function(){
- $('#add_host').click(function(){
- $('.shade,.add-modal').removeClass('hide');
- });
- $('#cancel').click(function(){
- $('.shade,.add-modal').addClass('hide');
- });
- $('#ajax_submit').click(function(){
- $.ajax({
- url: "/test_ajax",
- type: 'POST',
- {# data: {'hostname':$('#host').val(),'ip':$('#ip').val(),'port':$('#port').val(),'b_id':$('#sel').val()},#}
- data: $('#add_form').serialize(),
- success: function(data){
- var obj = JSON.parse(data);
- if(obj.status){
- location.reload();
- }else{
- $('#erro_msg').text(obj.error);
- }
- }
- })
- })
- $('.edit').click(function(){
- $('.shade,.edit-modal').removeClass('hide');
- var bid = $(this).parent().parent().attr('bid');
- var nid = $(this).parent().parent().attr('hid');
- $('#edit_form').find('select').val(bid);
- $('#edit_form').find('input[name="nid"]').val(nid);
- //修改操作了
- $.ajax({
- data: $('#edit_form').serialize()
- });
- //获取到models.Host.objects.filter(nid=nid).update()
- })
- })
- </script>
- </body>
- </html>
里面涉及的知识点:
1、拿到NID并隐藏,用于提交数据
2、使用ajax来提交数据