zoukankan      html  css  js  c++  java
  • DAY81-Django框架(十一)

    一、多对多创建第三张表的三种方式

    1.手动创建第三张表

    class Book(models.Model):
    	# 默认会创建id
     	name = models.CharField(max_length=32)
        
    class Author(models.Model):
        name = models.CharField(max_length=32)
        
    class Book2Author(models.Model):
        id = models.AutoField(primary_key=True)
        book=models.ForeignKey(to='Book',to_field='id')
        author=models.ForeignKey(to='Author',to_field='id')
        #不管是插入和查询,删除,都很麻烦(一般不用)
    

    2.通过ManyToMany自动创建第三张表

    class Book(models.Model):
        name = models.CharField(max_length=32)
        
    # 通过ORM自带的ManyToManyField自动创建第三张表
    class Author(models.Model):
        name = models.CharField(max_length=32)
        books=models.ManyToManyField(to="Book")
    #可以通过set,add,clear,remove来对数据增删改查,操作方便,但是第三张表的字段就固定了。
    

    3.通过ManyToMany手动创建第三张表,建立关联关系

    class Book(models.Model):
        # 默认会创建id
        name = models.CharField(max_length=32)
        # 中介模型,手动指定第三张中间表是Book2Author
    	authors=models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))
        #through:指定第三张表
        #through_fields(book,'author'):第一个值是第三张表中与当前表关联的字段;
    class Author(models.Model):
    	name = models.CharField(max_length=32)
    	def __str__(self):
    		return self.name
    class Book2Author(models.Model):
    	id = models.AutoField(primary_key=True)
    	book=models.ForeignKey(to='Book',to_field='id')
    	author=models.ForeignKey(to='Author',to_field='id')
        
    #最大的优点是可以在第三张表中添加额外字段,且比第一种方便
    

    二、AJAX

    1.什么是ajax

    ​ AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML。

    2.特点

    • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。
    • 热更新:浏览器页面局部刷新,这一特点给用户的感受是在不知不觉中完成请求和响应过程

    3.语法

    $.ajax({
        //url:指向路由
        url:'/index/',
        //type:传输方式
        type:'post',
        //data:往后台提交的数据
        data:{'name':'lqz','age':18},
        //成功的时候回调这个函数
        success:function (data) {
            alert(data)
        }
    })
    

    三、AJAX案例

    案例一

    用户在表单输入用户名与密码,通过Ajax提交给服务器,服务器验证后返回响应信息,客户端通过响应信息确定是否登录成功,成功,则跳转到百度,否则,在页面上显示相应的错误信息

    模板层ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.3.1.js"> </script>
    </head>
    <body>
    <form>
        <input type="text" placeholder="用户名" id="name">
        <input type="password" placeholder="密码" id="pwd">
        <h1 id="h1"></h1>
    </form>
        <button id="btn">登录</button>
    </body>
    <script>
        $('#btn').click(function () {
            get_data={'name':$('#name').val(),'pwd':$('#pwd').val()}
            $.ajax({
                url:'/ajax1/',
                type:'post',
                data:get_data,
                success:function(data){
                    if (data){
                        location.href="https://www.baidu.com";
                    }
                    else{
                        $('#h1').text('账号或密码错误')
                    }
                }
            })
        })
    </script>
    </html>
    

    视图层

    from django.shortcuts import render,HttpResponse
    from app01 import models
    from django.http import JsonResponse
    # Create your views here.
    
    def ajax1(request):
        if request.method=='GET':
            return render(request,'ajax.html')
    
        print(request.POST)
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        user_db = models.User.objects.filter(name=name,password=pwd).first()
        if user_db:
            return HttpResponse('1')
        else:
            return HttpResponse()
    

    案例二

    在上题的基础上,以JSON格式数据交互

    模板层ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.3.1.js"> </script>
    </head>
    <body>
    <form>
        <input type="text" placeholder="用户名" id="name">
        <input type="password" placeholder="密码" id="pwd">
    </form>
        <button id="btn">登录</button>
        <h1 id="h1"></h1>
    </body>
    <script>
        $('#btn').click(function () {
            var get_data={'name':$('#name').val(),'pwd':$('#pwd').val()}
    
            $.ajax({
                url:'/ajax1/',
                type:'post',
                //JSON.stringify():转化为JSON格式
                data:JSON.stringify(get_data),
                //请求的编码格式:json
                contentType:'application/json',
                //响应的解析方式:json,将后台给的数据转为JSON
                dataType:'json',
                success:function(data){
                    console.log(data)
                    console.log(typeof data)
                    //JSON.parse(data):把后台传来的数据再转为JSON格式,注意,如果后台已经使用JsonResponse传数据,再用会报错
                    if (data.code){
                        location.href="https://www.baidu.com";
                    }
                    else{
                        $('#h1').text(data.msg)
                    }
                }
            })
        })
    
    </script>
    </html>
    

    视图层

    from django.shortcuts import render,HttpResponse
    from app01 import models
    import json
    from django.http import JsonResponse
    # Create your views here.
    
    def ajax1(request):
        dic={'code':None,'msg':None}
        if request.method=='GET':
            return render(request,'ajax.html')
        # JSON编码是在放在body
        res = json.loads(request.body.decode('utf-8'))
        print(res)
        name = res['name']
        pwd = res['pwd']
        user_db = models.User.objects.filter(name=name,password=pwd).first()
        if user_db:
            dic['code']=user_db.name
        else:
            dic['code'] = user_db
            dic['msg']='账号或密码错误'
            #
        return JsonResponse(dic) #或return HttpResponse(json.dumps(dic))
    

    总结

    使用JSON数据交互

    ​ 前端----->后台:JSON.stringify()

    ​ 后台----->前台:

    ​ 1.后台使用JsonResponse(dic),前台无需转换格式

    ​ 2.后台使用HttpResponse(json.dumps(dic)),前台使用dataType:'json' 或者 JSON.parse(data)

    案例三

    json格式的文件上传

    模板层

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.3.1.js"> </script>
    </head>
    <body>
    <form>
        <input type="text" id="name">
        <input type="file" id="up">
    </form>
    <button id="btn">上传</button>
    </body>
    <script>
        $('#btn').click(function () {
            //上传文件,必须用FormData,生产一个formdata对象
            var formdata= new FormData()
            //取出文件$("#up")[0].files拿到的是文件列表,取第0个把具体的文件取出来
            formdata.append('myfiles',$('#up')[0].files[0]);
            formdata.append('name',$('#name').val())
            console.log(formdata)
            $.ajax({
                url:'/files/',
                type:'post',
                data:formdata,
                //processData:true默认,处理data的数据;false,不去处理数据
                processData:false,
                //contentType:指定往后台传数据的编码格式(urlencoded默认,formdata,json);false,不指定编码
                contentType:false,
                success:function (data) {
                    alert(data)
                }
            })
        })
    </script>
    </html>
    

    视图层

    def files_up(request):
        if request.method=='GET':
            return render(request,'files.html')
        print(request.body)
        print(request.POST)
        print(request.FILES)
        name = request.POST.get('name')
        print(name)
        myfile = request.FILES.get('myfiles')
        with open(myfile.name, 'wb') as f:
            # 循环上传过来的文件
            for line in myfile:
                # 往空文件中写
                f.write(line)
        return HttpResponse('ok')
    

  • 相关阅读:
    Entity SQL 初入
    ObjectQuery查询及方法
    Entity Framework 的事务 DbTransaction
    Construct Binary Tree from Preorder and Inorder Traversal
    Reverse Linked List
    Best Time to Buy and Sell Stock
    Remove Duplicates from Sorted Array II
    Reverse Integer
    Implement Stack using Queues
    C++中const限定符的应用
  • 原文地址:https://www.cnblogs.com/xvchengqi/p/9984883.html
Copyright © 2011-2022 走看看