Django之 Choices参数、MVC和MTV模型、Ajax

目  录

  • Choices参数

  • MVC和MTV模型

  • Ajax

一、Choices参数

在应用app01中的models.py文件下,建模型表类Teacher

from django.db import models

# Create your models here.
class Teacher(models.Model):
    username = models.CharField(max_length=32)
    password = models.IntegerField(default=123)
    choices = (
        (1,'male'),
        (2,'female'),
        (3,'others')
    )
    gender = models.IntegerField(choices=choices)

引出Choices字段:

    choices = (
    (1,'male'),
    (2,'female'),
    (3,'others')
    )
    gender = models.IntegerField(choices=choices)
    """
    1.如果我存的是上面元组中数字会怎么样
    2.如果我存的数字不在元组范围内又会怎样
        1.数字没有对应关系 是可以存的
    """

在测试文件夹test.py下获取数据:

from django.test import TestCase

# Create your tests here.
import os

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day62.settings")
    import django
    django.setup()


    from app01 import models
    t_obj = models.Teacher.objects.filter(pk=1).first()
    print(t_obj.username)
    print(t_obj.password)
    print(t_obj.get_gender_display())
    '''
    由以上代码可知:针对choices字段如果想要获得对应的中文,不能直接点语法,
    要有固定句式, 数据对象.get_字段名_display;
    如果choices字段中没有对应的关系,那么执行语句:print(t_obj.get_gender_display())只能得到对应的数字
    '''

Choices字段示例:

record_choices = (('checked', "已签到"),
                  ('vacate', "请假"),
                  ('late', "迟到"),
                  ('noshow', "缺勤"),
                  ('leave_early', "早退"),
                  )
    record = models.CharField("上课纪录", choices=record_choices, default="checked", 
示例1
 score_choices = ((100, 'A+'),
                 (90, 'A'),
                 (85, 'B+'),
                 (80, 'B'),
                 (70, 'B-'),
                 (60, 'C+'),
                 (50, 'C'),
                 (40, 'C-'),
                 (0, ' D'),
                 (-1, 'N/A'),
                 (-100, 'COPY'),
                 (-1000, 'FAIL'),
                 )
    score = models.IntegerField("本节成绩", choices=score_choices, default=-1)
示例2

二、MVC和MTV模型

MTV模型:

M  ——    models  模型层

T ——  templates   模板层

V  ——  views   视图层

MVC模型:

M ——  models 模型层

V ——  views   视图层

C ——   contronner  路由匹配

Django框架虽然号称是MTV模型,但是实际上也是MVC模型。

三、Ajax

1、AJAX简介

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

2、AJAX特点

AJAX最大的优点可以在不重新加载整个页面的情况下,与服务器交互数据并进行局部刷新(局部刷新:就是一个页面不是整体刷新,而是某个地方刷新。。。)

3、知识回顾

同步异步:任务的提交方式

同步 —— 就是执行完代码后,原地等待执行的结果,期间不做任何事

异步 —— 执行完一段代码后,不会原地等待结果,而是跳过去执行下一段代码,任务的返回结果通过回调机制获取。

阻塞非阻塞:指的是程序的运行状态。程序的运行状态有就绪态、运行态、和阻塞态。

总结:

AJAX是一门js技术,它基于原生的js代码进行开发,但是原生的js代码过于繁琐,所以我们学习使用jQuery实现ajax。

案例1:

展示一个前端页面,有3个输入框,前两个输入框输入数字,在不重新加载页面的情况下完成这两个数字的加法运算。

前端页面html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="t1"> + <input type="text" id="t2"> = <input type="text" id="t3">
<p>
    <button id="b1">计算</button>
</p>

<script>
    $('#b1').on('click',function () {
        // 朝后端提交post数据
        $.ajax({
            // 1.到底朝后端哪个地址发数据
            url:'',  // 专门用来控制朝后端提交数据的地址  不写默认就是朝当前地址提交
            // 2.到底发送什么请求
            type:'post',  // 专门制定ajax发送的请求方式
            // 3.发送的数据到底是什么
            data:{'t1':$('#t1').val(),'t2':$('#t2').val()},
            data:{'username':'jason','password':'123'},
            // 4.异步提交的任务 需要通过回调函数来处理
            success:function (data) {  // data形参指代的就是异步提交的返回结果
                // 通过DOM操作将内容 渲染到标签内容上
                $('#t3').val(data)  // 注意: 这个data是回调函数的返回值,与上面的data不一样,具体对应的是jiafa函数中的HttpResponse(res)
                alert(data)
            }
        })
</script>
</body>
</html>

视图层函数:

def jiafa(request):
    print(request.is_ajax())  #  先判断是不是ajax请求
    if request.is_ajax():
        if request.method == 'POST':
            t1 = request.POST.get('t1')
            t2 = request.POST.get('t2')
            res = int(t1)+ int(t2)
            return HttpResponse(res)

    return render(request,'jiafa.html')

前后端传输数据的编码格式

contentType前后端数据的编码格式:

以form表单为例,提出问题:

为什么form表单参数enctype默认情况下只能得到文件名?

contentType前后端传输数据编码格式

    form表单 默认的提交数据的编码格式是urlencoded
        urlencoded
            username=admin&password=123这种就是符合urlencoded数据格式
            
            django后端针对username=admin&password=123的urlencoded数据格式会自动解析
            将结果打包给request.POST 用户只需要从request.POST即可获取对应信息
           
        formdata
            django后端针对formdata格式类型数据 也会自动解析
            但是不会方法request.POST中而是给你放到了request.FILES中
        
    ajax  ajax默认的提交数据的编码格式也是urlencoded
        username=jason&password=123
        
    总结:django后端针对不同的编码格式数据 会有不同的处理机制以及不同的获取该数据的方法

"""
前后端在做数据交互的时候 一定一定要表明你所发的的数据到底是什么格式

前段后交互 你不能骗人家
你的数据时什么格式 你就应该准确无误告诉别人是什么格式   
"""

ajax传json格式的数据

ajax传文件

猜你喜欢

转载自www.cnblogs.com/qinsungui921112/p/11755551.html