20.django

1.ajax 使用

======index.html========
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="/static/jquery-1.12.4.js"></script>
    <script  async src="/static/test.js"></script>
</head>
<body>
        <input type="button" value="异步获取数据" />
        <div id="box"></div>
</body>

</html>
=======test.js==========
$(function(){
    //一 $.get使用方法
    /* url后直接传参
    $('input').click(function(){
        $.get('/test/?nid=ycku',function(response,status,xhr){
            $('#box').html(response);
        });
    });
    */
    /*通过第二个参数data,字符串形式的键值对传参
     $('input').click(function(){
        $.get('/test/','nid=ycku',function(response,status,xhr){
            $('#box').html(response);
        });
    });
    */

    /* 第三通过data,对象形式的键值对传参
    $('input').click(function(){
        $.get('/test/',{
            nid:'ycku'
        },function(response,status,xhr){
            $('#box').html(response);
        });
    });
    */
    //二 $.post使用方法
    /* post不能使用问号传参 */
    /* 1.可以使用字符串形式传参
    $('input').click(function(){
        $.post('/test/','nid=ycku',function(response,status,xhr){
            $('#box').html(response);
        });
    });
    */
    /*2.可以使用对象形式的键值对传参*/

    /*
     $('input').click(function(){
        $.post('/test/',{
            nid:'ycku'
        },function(response,status,xhr){
            $('#box').html(response);
        },'xml');    //djanog文件返回的是纯文本,默认是html或text
    });
    //本身是纯文本,如果强行按照xml或者json数据格式返回的话,那么就无法获取数据
   */
    /*第三 $.ajax对于get属性中data继续使用于上面的三种方法,Post试用于上面的两种方法
    $('input').click(function(){
        $.ajax({
            type:'POST',
            url:'/test/',
            data:{
                nid:'ycku',
            },
            success:function(response,status,xhr){
                $('#box').html(response);
            }
        });
    });


});

=====views.py========
def index(request):
    return render(request,'index.html')


def test(request):

    if request.method == 'GET':
        nid = request.GET.get('nid')
        print (nid)
        if nid == 'ycku':
            return HttpResponse('get泡成Web俱乐部')
        else:
            return HttpResponse('Get木有')
    elif request.method == 'POST':
        nid = request.POST.get('nid')
        if nid == 'ycku':
            return HttpResponse('post泡成Web俱乐部')
        else:
            return HttpResponse('Post木有')
    else:
        return HttpResponse('Error!')

=======urls.py=======
from django.conf.urls import url
from django.contrib import admin
from App01 import views

urlpatterns = [
    url(r'^index/',views.index),
    url(r'^test/',views.test),
]

 2.表单获取数据的三种方式:

======pbusiness.html=======
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>获取元素列表(对象)</h1>
    <table border="1">
        <thead>
            <tr>
                <td>id</td>
                <td>组名</td>
                <td>管理员</td>
            </tr>
        </thead>
        <tbody>
            {% for row in groups %}
                <tr>
                    <td>{{ row.id }}</td>
                    <td>{{ row.caption }}</td>
                    <td>{{ row.code }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>获取元素列表(字典)</h1>
    <table border="1">
        <thead>
            <tr>
                <td>id</td>
                <td>组名</td>
                <td>管理员</td>
            </tr>
        </thead>
        <tbody>
            {% for row in group_values %}
                <tr>
                    <td>{{ row.id }}</td>
                    <td>{{ row.caption }}</td>
                    <td>{{ row.code }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <h1>获取元素列表(列表)</h1>
    <table border="1">
        <thead>
            <tr>
                <td>id</td>
                <td>组名</td>
                <td>管理员</td>
            </tr>
        </thead>
        <tbody>
            {% for row in group_values_list %}
                <tr>
                    <td>{{ row.0 }}</td>
                    <td>{{ row.1 }}</td>
                    <td>{{ row.2 }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>

========views.py=========
def show_group(request):
    group = models.PBusiness.objects.all()
    group_values = models.PBusiness.objects.values('id','caption')
    group_values_list = models.PBusiness.objects.values_list('id', 'caption','code')

    return render(request,'pbusiness.html',{'groups':group,'group_values':group_values,'group_values_list':group_values_list})

===========models.py======
class PBusiness(models.Model):
    caption = models.CharField(max_length=32)
    code = models.CharField(max_length=64)



class Phost(models.Model):
    nid= models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.CharField(max_length=5)
    phost_group = models.ForeignKey(to='PBusiness',to_field='id')

3.django数据库增、删、改、查总结

增加:
    models.User.objects.create(name='qianxiaobu',age=18)
    dic = {'name':'xx','age':19}
    models.User.objects.create(**dic)

    obj = models.User(name='qianxiaohu',age=19)
    obj.save()
删除:
   models.User.objects.filter(id=1).delete()
修改:
   models.User.objects.filter(id__gt=1).update(name='alex',age=84)
   dic = {'name':'xx','age':19}
   models.User.objects.filter(id__gt=1).update(**dic)
查找:
   models.User.objects.filter(id=1,name='root')
   models.User.objects.filter(id__gt=1,name='root')
   models.User.objects.filter(id__lt=1)
   models.User.objects.filter(id__gte=1)
   models.User.objects.filter(id__lte=1)

   models.User.objects.filter(id=1,name='root')
   dic = {'name':xx,'age__gt':19}
   models.User.objects.filter(**dic)

   v1 = models.Business.objects.all()
   #以上,内部元素都是对象

   v2 = models.Business.objects.all().values('id','caption')
   #v2内部元素为字典
   v3 = models.Business.objects.all().values_list('id','caption')
   #v3内部元素为元祖


   models.Business.objects.get(id=1)      #获取一个对象)(单个值),如果不存在就报错
   models.Business.objects.filter(id=1)   #获取QuerySet ,有内容输出,没有内容为None
   models.Business.objects.filter(id=1).first()   #获取为对象,不存在返回为None

    

4.表的行序列号

forloop.counter
forloop.counter0  #从0开始
forloop.revcounter  #倒叙排
forloop.revcounter0
forloop.last    #是否是最后一个循环
forloop.first    #是否是第一循环
forloop.parentloop   #在嵌套循环中,上一层循环的结果是多少



实例:

                {% for row in groups %}
                    <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.phost_group.caption }}</td>
                    </tr>
                {% endfor %}

5.Post方法添加数据到数据库:

==========phost.html===========
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .shadow{
            position:fixed;
            top:0;
            left:0;
            right:0;
            bottom:0;
            background:black;
            opacity:0.5;
            z-index:8;
        }
        .add-modal{
            position:fixed;
            height:400px;
            width:500px;
            top:200px;
            left:50%;
            margin-left:-200px;
            z-index:9;
            border:green;
            background:white;
        }
    </style>
</head>
<body>
 <h1>主机列表(对象)</h1>
    <div>
        <input id="add_host1" 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 groups %}
                    <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.phost_group.caption }}</td>
                    </tr>
                {% endfor %}


        </tbody>
    </table>
    <div class="shadow hide"></div>
    <div class="add-modal hide">
        <form action="/show_host/" method="post">
            <div class="group">
                <input id='hostname' 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 groups %}
                        <option value="{{  op.phost_group_id }}" >{{ op.phost_group.caption  }}</option>
                    {% endfor %}
                </select>
            </div>
            <input id="add_host2" type="submit" value="提交">
            <a id="ajax_sub" >ajax提交</a>
            <input id='cancel' type="button" value="取消">
        </form>
    </div>

    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function(){
            $('#add_host1').click(function(){
                $('.shadow,.add-modal').removeClass('hide');
            });
            $('#cancel').click(function(){
                $('.shadow,.add-modal').addClass('hide');
            });
            
            });
        });
    </script>
</body>
</html>

=========views.py========
def show_host(request):
    if request.method == 'GET':
        group = models.Phost.objects.all()
        print ("group=",type(group))
        group_values = models.Phost.objects.values('nid','hostname','ip','port','phost_group__caption','phost_group__code')
        print ("group_values=",type(group_values))
        group_values_list = models.Phost.objects.values_list('nid','hostname','ip','port','phost_group_id','phost_group__caption','phost_group__code')
        print ("group_values=",type(group_values_list))

        return render(request,'phost.html',{'groups':group,'group_values':group_values,'group_values_list':group_values_list})
    elif request.method =='POST':
        hostname  = request.POST.get('hostname')
        ip = request.POST.get('ip')
        port = request.POST.get('port')
        business = request.POST.get('b_id')

        models.Phost.objects.create(hostname=hostname,ip=ip,port=port,phost_group_id=business)
        print (hostname,ip,port,business)

        return redirect('/show_host/')
    else:
        return HttpResponse('Error!')

========urls.py=========
url(r'^show_host/$',views.show_host)

6.通过ajax方法提交表单到数据库

 

=======phost.htmll==========
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .shadow{
            position:fixed;
            top:0;
            left:0;
            right:0;
            bottom:0;
            background:black;
            opacity:0.5;
            z-index:8;
        }
        .add-modal,.edit-modal{
            position:fixed;
            height:400px;
            width:500px;
            top:100px;
            left:50%;
            margin-left:-200px;
            z-index:9;
            border:green;
            background:white;
        }
    </style>
</head>
<body>
 <h1>主机列表(对象)</h1>
    <div>
        <input id="search" type="text"  />
        <input 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 groups %}
                    <tr hid="{{ row.nid }}" bid="{{ row.phost_group_id }}">
                        <td>{{ forloop.counter }}</td>
                        <td rhost = "{{ row.hostname }}">{{ row.hostname }}</td>
                        <td rip = "{{ row.ip }}">{{ row.ip }}</td>
                        <td rport = "{{ row.port }}">{{ row.port }}</td>
                        <td rcaption = "{{ row.phost_group.caption }}">{{ row.phost_group.caption }}</td>
                        <td>
                            <a class="add" style="color:green">添加</a>
                            |
                            <a id='aedit' class="edit" style="color:blue">编辑</a>
                            |
                            <a class="delete" style="color:red">删除</a>
                        </td>
                    </tr>
                {% endfor %}
        </tbody>
    </table>
    <div class="shadow hide"></div>
    <div class="add-modal hide">
        <form action="/show_host/"  method="post">
            <div class="group">
                <input id='hostname' 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 id="add_host2" type="submit" value="POST提交">
            <input id="ajax_sub" type="button" value="ajax提交" >
            <input id='cancel' type="button" value="取消">
        </form>
    </div>


 <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function(){
            $('.add').click(function(){
                $('.shadow,.add-modal').removeClass('hide');
            });
            $('#cancel').click(function(){
                $('.shadow,.add-modal').addClass('hide');
            });
            $('#cancel1').click(function(){
                $('.shadow,.edit-modal').addClass('hide');
            });
            $('#ajax_sub').click(function(){
                $.ajax({
                    url:"/show_host/",
                    type:'POST',
                    data:{
                        'hostname':$('#hostname').val(),
                        'ip':$('#ip').val(),
                        'port':$('#port').val(),
                        'sel':$('#sel').val()
                    },
                    success:function(response){
                        if (response == 'OK'){
                           location.reload() ;
                        }else{
                            alert("插入失败");
                        }
                    }
                });
            });

7.多对多关系:

方式一,自定义方式:
class Phost(models.Model):
    nid= models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.CharField(max_length=5)
    phost_group = models.ForeignKey(to='PBusiness',to_field='id')


class PApp(models.Model):
    name = models.CharField(max_length=32)


class HostToApp(models.Model):
    hobj = models.ForeignKey(to='Phost',to_field='nid')
    aobj = models.ForeignKey(to='PApp',to_field='id')

方式二,自动方式
class Phost(models.Model):
    nid= models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.CharField(max_length=5)
    phost_group = models.ForeignKey(to='PBusiness',to_field='id')



class App(models.Model):
    name = models.CharField(max_length=32)
    r = models.ManyToManyField('Phost')

8.多对多方式的添删改查

class Phost(models.Model):
    nid= models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=32,db_index=True)
    ip = models.GenericIPAddressField(db_index=True)
    port = models.CharField(max_length=5)
    phost_group = models.ForeignKey(to='PBusiness',to_field='id')

class App(models.Model):
    name = models.CharField(max_length=32)
    r = models.ManyToManyField('Phost')

注意:多对多关系无法直接对第三张表进行操作
obj = App.objects.get(id=1)
obj.name

obj.r.add(1)    #在第三章表中增加1对应1      hobj=1  aobj=1
obj.r.add(2,3,4)    
obj.r.add(*[1,2,3])

obj.r.remove(1)
obj.r.remove(2,3,4)
obj.r.remove(*[1,2,3])

obj.r.clear()   #清除app为1的所有的行

obj.r.set([3,5,7])   #删除所有aobj为1的,添加aobj为1的,hobj为3,5,7的内容

obj.r.all()   #所有相关的主机对象 Queryset

 

posted @ 2016-12-20 17:22  jidi_78  阅读(70)  评论(0)    收藏  举报