field choices, MTV and MVC model, AJAX, contentType front end of the transmission data coding format, the sequence of components, AJAX + sweetalert use

field choices, MTV and MVC model, AJAX, serialization component, AJAX + sweetalert use

choices field

Mainly used in some special characters or numbers on behalf of tedious string, the one to save data space, and secondly for data readability. It can be used to enter a user gender, user education, work status.

eg: create a user table, including the gender field, you can use the choices field by numbers instead of the corresponding sex characters.

from django.db import models
class Userinfo(models.Model):
    username = models.CharField(max_length=64)
    # choices字段,用元组形式
    choices = (
        (1, 'male'),
        (2, 'female'),
    )
    gender = models.IntegerField(choices=choices)  # 这一句很重要,choices一定要等于定义的那个变量名

Note that if we exist in the table above is a tuple of numbers, it appears, but the numbers do not correspond to also be saved to the table, but the point get_gender_displaydoes not get the number corresponding Chinese syntax to take, but will get to that number, so there is no corresponding relationship, keep this number will not make sense.

Choices for the field, if you want to get numbers corresponding to the Chinese, not directly point field,

Fixed sentence: 数据对象.get_字段名_display()when there is no corresponding relationship, the sentence acquired or digital

eg:

from app01 import models
user_obj = models.Userinfo.objects.filter(pk=4).first()
print(user_obj.username)
print(user_obj.gender)   # 这样的结果只是数字
print(user_obj.get_gender_display())   # 有对应关系的时候,该句式就能获取到数字对应的中文

For the aforementioned user information table, we can create the class record and give it in this section score Fields with choices field

# 创建上课记录字段,用特殊的字符来代表繁琐的字符串
record_choices = (('checked', "已签到"),
                      ('vacate', "请假"),
                      ('late', "迟到"),
                      ('noshow', "缺勤"),
                      ('leave_early', "早退"),
                      )
record = models.CharField("上课纪录", choices=record_choices, default="checked", max_length=255)
 
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)

MTV and MVC model

django framework known as MTV, in fact, it is the MVC framework

The MTV:
M: Models
T: Templates
V: views
the MVC:
M: Models
V: views
C: contronner (route matches)

ajax

AjaX js is a technology based on native js development, but to write code with native js too cumbersome

The biggest advantage is AjaX without reloading the entire page, you can exchange data with the server and update parts of the page content. (This feature is the feeling to the user request and response process is completed unknowingly)

Features:

  • Asynchronous submitted

    Synchronous Asynchronous: submission tasks described

    Synchronization: After submission of the task, return to their home to wait for the results of the task, not do anything during the

    Asynchronous: After submission of the task, do not wait and directly next line of code, return to the task through a callback mechanism

    Blocking non-blocking: the program running

    Three running state of FIG.

  • Partial refresh

    Not a whole page refresh, but somewhere partial page refresh

For example: shows a front page, a case where there are three input box, the first two frames of the input digital, click the button toward the rear end of the retransmission request, the page without refreshing the page, the complete digital adder

ajax_test.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>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.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()},
        // 4.异步提交的任务,需要通过回调函数来处理
        success:function (data) {  // data形参指代的就是异步提交的返回结果
            // 通过DOM操作将内容渲染到标签内容上
            $('#t3').val(data)
        }
    })
})
</script>
</body>
</html>

views.py

from django.shortcuts import render, HttpResponse
def ajax_test(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, 'ajax_test.html')

urls.py

from django.contrib import admin
from django.conf.urls import url
from homework1018 import views
urlpatterns = [
    url('admin/', admin.site.urls),
    url('^ajax_test/', views.ajax_test),
]

Data transfer format ajax json

Front and rear end when doing data exchange must be sure to indicate that you send the data in the end is what format.
When you can not lie to interact after the preceding home, what format you should be accurate when you tell someone what data format.

In the example described above is an example, data transmission format json

Precautions
1. Specify contentType parameter
contentType:'application/json',
2. To make sure that the data you send is json format
data:JSON.stringify({'username':'jason','password':'123'})

Front page

<p>
    <button id="b1">计算</button>
</p>
<script>
$('#b1').on('click',function () {
    // 朝后端提交post数据
    $.ajax({
        // 1.到底朝后端哪个地址发送数据
        url:'',  // 专门用来控制朝后端提交数据的地址,不写默认朝当前地址提交
        // 2.指定到底发送什么请求
        type:'post',  // 专门制定ajax发送的请求方式
        // 3.告诉后端你当前的数据格式到底是什么类型
        contentType:'application/json',  // 告诉后端当前数据格式是json类型
        // 4.发送的数据是什么
        data:JSON.stringify({'username':'jason','password':'123'}),
        // 5.异步提交的任务,需要通过回调函数来处理
        success:function (data) {  // data形参指代的就是异步提交的返回结果
            // 通过DOM操作将内容渲染到标签内容上
            alert(data)
        }
    })
})
</script>

Back-end data acquisition

django backend json format for the data will not automatically help you to resolve intact will put you in direct request.body
get the data, you can manually handle the format:

    json_bytes = request.body
    json_str = str(json_bytes,encoding='utf-8')
    json_dict = json.loads(json_str)
from django.shortcuts import render, HttpResponse, redirect
import json
def ajax_test(request):
    if request.method == 'POST':
        # django后端针对json格式的数据不会自动帮你解析,会直接原封不动的给你放到request.body中
        # 你可以手动处理,获取数据
        # print(request.body)  # b'{"username":"jason","password":"123"}'
        json_bytes = request.body
        json_str = str(json_bytes, encoding='utf-8')  # 将bytes格式转化为字符串
        json_dict = json.loads(json_str)   # 将字符串序列化
        print(json_dict, type(json_dict))
    return render(request, 'ajax_test.html')

ajax transfer files

Ajax file transfer issues should be noted

1. formdata using simple objects can quickly transfer data (Normal + key file)

Generating a formdata objects: var myFormData = new FormData()

2. There are several parameters
data: formdata Object
contentType: false # formdata objects without any coding because coding comes django able to identify the object
processData: false # tell the browser not to send my data directly on the line

3. The need to use the built-in object: FormData
the object can either pass an ordinary key can also transfer files

4. The user acquires the content input box files uploaded
1 to find that tag jquery by
2. converting the object into native jquery js objects
3. The use of native methods js direct access to the object file contents
eg:$('#t3')[0].files[0]

Front page upload.html

<body>
<input type="text" name="username" id="t1">
<input type="text" name="password" id="t2">
<input type="file" name="myfile" id="t3">
<button id="b1">提交</button>
<script>
    $('#b1').click(function () {
        // 1.先生成一个formdata对象
        var myFormData = new FormData();
        // 2.朝对象中添加普通的键值
        myFormData.append('username',$("#t1").val());
        myFormData.append('password',$("#t2").val());
        // 3.朝对象中添加文件数据
        // 1.先通过jquery查找到该标签
        // 2.将jquery对象转换成原生的js对象
        // 3.利用原生js对象的方法 直接获取文件内容
        myFormData.append('myfile',$('#t3')[0].files[0]);
        $.ajax({
            url:'',
            type:'post',
            data:myFormData,  // 直接丢对象
            // ajax传文件 一定要指定两个关键性的参数
            contentType:false,  // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
            processData:false,  // 告诉浏览器不要处理我的数据 直接发就行
            success:function (data) {
                alert(data)
            }
        })
    })
</script>
</body>

rear end

def upload(request):
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
            return HttpResponse('收到啦 dsb')
    render(request, 'upload.html')

contentType front end of the transmission data coding format

submission of data form form default encoding format is urlencoded
urlencoded
username = ADMIN & password = 123 This is in line with urlencoded data format
django backend for the username = admin & password = urlencoded data format 123 will automatically parse
the results package to request.POST users only the need to obtain the corresponding information from request.POST

formdat to

django backend for formdataautomatically parse data format type, but will not put request.POSTin but put request.FILESthe

Data submitted ajax ajax default encoding format is urlencoded.

Summary: django backend coding for different data formats, there will be different mechanisms and different methods of obtaining the data.

Use of ajax + sweetalert

sweetalertWhat the hell is it? He bootstrapis a big difference between not bad, we downloaded the file down the line, ajax + sweetalertyou will realize what an effect it? He is in us to delete a row of data when a pop-up drop-down box, we mainly do is to do this thing drop-down box to pass the back-end, back-end data in the database and then deleted.

Front page

<!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>
{#    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">#}
{#    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>#}
    {% load static %}
   {% load static %}
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'dist/sweetalert.min.js' %}"></script>
    <style>
        div.sweet-alert h2 {
            padding-top: 10px;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h2>数据展示</h2>
            <table class="table table-hover table-striped table-bordered">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>性别</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user_obj in user_queryset %}
                        <tr>
                            <td>{{ forloop.counter }}</td>
                            <td>{{ user_obj.username }}</td>
                            <td>{{ user_obj.get_gender_display }}</td>
                            <td>
                                <a href="#" class="btn btn-primary btn-sm">编辑</a>
                                <a href="#" class="btn btn-danger btn-sm cancel" delete_id="{{ user_obj.pk }}">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    $('.cancel').click(function () {
        var $btn = $(this);
        swal({
          title: "你确定要删吗?",
          text: "你要是删了,你就准备好跑路吧!",
          type: "warning",
          showCancelButton: true,  // 是否显示取消按钮
          confirmButtonClass: "btn-danger",  // 确认按钮的样式类
          confirmButtonText: "对,老子就要删!",  // 确认按钮文本
          cancelButtonText: "算了,算了!",  // 取消按钮文本
          closeOnConfirm: false,   // 点击确认按钮不关闭弹框
          showLoaderOnConfirm: true   // 显示正在删除的动画效果
        },
        function(){
            $.ajax({
                url:'',
                type:'post',
                data:{'delete_id':$btn.attr('delete_id')},
                success:function (data) {
                    if (data.code==1000){
                        swal(data.msg, "你可以回去收拾行李跑路了.", "success");
                        // 1.直接刷新页面
                        {#window.location.reload()#}
                        // 2.通过DOM操作 实时删除
                        $btn.parent().parent().remove()  // 对这个删除的标签的父级标签进行操作,删除它的父级标签,这里是直接操作该条数据的tr标签
                    }else{
                        swal("发生了未知错误!", "我也不知道哪里错了.", "info");
                    }
                }
            });

        });
    })
</script>

</body>
</html>

rear end

"""
当你是用ajax做前后端 交互的时候 
你可以考虑返回给前端一个大字典
"""
from homework1018 import models
import time
from django.http import JsonResponse
def sweetajax(request):
    if request.method == 'POST':
        back_dic = {"code":1000,'msg':''}  # 定义一个空字段,记录操作,到时候直接返回给前端
        delete_id = request.POST.get('delete_id')  # 获取要删除数据的id
        models.Userinfo.objects.filter(pk=delete_id).delete()
        back_dic['msg'] = '后端传来的:真的被我删了'  # 如果删除了,就会返回这样一个字典,也代表这个字典是从后端传来的
        time.sleep(3)  # 模拟删除时间
        return JsonResponse(back_dic)
    user_queryset = models.Userinfo.objects.all()
    return render(request, 'sweetajax.html', locals())

Serialization assembly

Automatically help you serialize some data

eg: the query returns data to the user table out of the front end, to the distal end is a large dictionary, the dictionary data is one field

rear end

front end

<body>
    {{ res }}  # 把后端的res传过来,能代替下面一大段代码,把数据展示到前端页面上
    
    {#{% for foo in user_list %}#}
    {#<p>{{ foo.username }}</p>#}
    {#<p>{{ foo.password }}</p>#}
    {#<p>{{ foo.gender }}</p>#}
    {#{% endfor %}#}
</body>

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11756367.html