Django-5

Django-5

choice parameters

In the process of creating a table, if you encounter duplicate data, we can use numbers instead of the corresponding record in this field, such as gender, only men and women, so we can better define in advance gender categories, 1 male, 2 female representation, then we can insert the data directly using the correspondence relationship.

choices = (
        (1,'male'),
        (2,'female'),
        (3,'others')
        )
gender = models.IntegerField(choices=choices)

When you take it directly to gender field, displayed or digital, how to get the correspondence between the digital representation of it?

user_obj = models.Userinfo.objects.filter(pk=4).first()
print(user_obj.get_gender_display())  
# 固定句式   数据对象.get_字段名_display()

Note : Sometimes, when taken out of the correspondence between when a custom correspondence relationship, when not, take out the still figure.

MTV and MVC model

MTV is known as Django framework, in essence, it is the MVC framework. Asynchronous submitted

  • MTV:
    • M : models
    • T : templates
    • V: views
  • MVC:
    • M : models
    • V: views
    • C: contronner (routing assignment)

Ajax asynchronous submit

Synchronous Asynchronous : submission tasks described

  • Synchronization: In-situ during the return of the task awaiting the results of any thing quit after submitting mission
  • Asynchronous : After submission of the task do not want to wait for the next line of code to perform tasks directly returned by the callback mechanism

Partial refresh : a page, not the overall refreshing, but somewhere in the partial refresh the page.

AJAX is not a new programming language, but a new method of using existing standards (js is a technology based on the development of native js).

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)

AJAX does not require any browser plug-ins, but requires the user to allow the execution of JavaScript in the browser.

  • Synchronous interaction: The client sends a request, it must wait for the end of the server response before sending the second request;
  • Asynchronous interactions: the client sends a request to the server without waiting for the end of the response, it can issue a second request.

Ajax syntax will

# views.py
def add(request):
    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, 'add.html')

# add.html
    <h1>A+B=???</h1>
    <p>A:<input type="text" class="form-control a"></p>
    <p>B:<input type="text" class="form-control b"></p>
    <p>C:<input type="text" class="form-control c"></p>
    <br>
    <button id="btn">计算</button>

<script>
    $('#btn').on('click',function () {
        $.ajax({
            url:'',
            type:'post',
            {#contentType:'application/json',#}
            data:{'t1':$('.a').val(),'t2':$('.b').val()},
            success:function (data) {
                $('.c').val(data)
                $('.a').val('')
                $('.b').val('')
                alert('计算成功!')
            }
        })
    })
</script>

# 分析:
url:'', : 专门用来控制朝后端提交数据的地址,不写默认就是朝当前地址提交。
type:'', : 专门指定Ajax发送得到请求方式。
contenType:'', : 告诉后端你当前的数据格式到底是什么类型。
data:'', : 向后端发送的数据。
success:function(data){} : data形参指代的是异步提交的返回结果,success指定回调函数,可对后端返回数据做处理。

Ajax Json format data transfer

Django backend json format for the data, and will not automatically help you resolve, directly into intact to you request.body, you can manually process, retrieve data.

$("#btn").on('click',function () {
    $.ajax({
        url:'',
        type:'post',
        // 指定提交的数据的类型为json
        contentType:'application/json',
        // 将自定义对象序列化为json数据。
        data:JSON.stringify({'username':'nick','password':'123'}),
        success:function (data) {
            alert(data)
        }
    })
})

def index(request):
    # 判断提交方式是否为Ajax
    if request.is_ajax():
        if request.method == 'POST':
            json_data = str(request.body,encoding='utf8')
            json_dic = json.loads(json_data)
            print(json_dic,type(json_dic))
            return HttpResponse(json_dic)
    return render(request,'index.html')

Ajax transfer files

  • Need to use the built-in object Formdata
  • The object can pass both ordinary keys can also transfer files
<body>
<input type="text" name="username" id="a">
<input type="text" name="password" id="b">
<input type="file" name="myfile" id="c">
<button id="btn">提交</button>
<script>
    $('#btn').on('click',function () {
       // 生成form_data对象
        var form_data = new FormData();
        在form_data对象中添加普通的键值
        form_data.append('username',$('#a').val());
        form_data.append('password',$('#b').val());
        // 朝form_data对象中添加文件数据
            // 1.先通过jquery查找到该标签
            // 2.利用索引0转换成原生的js对象
            // 3.利用原生s对象的file()方法,直接获取文件的内容
        form_data.append('myfile',$('#c')[0].files[0]);
        $.ajax({
            url:'',
            type:'post',
            data:form_data, // 直接将对象当作数据
            contentType:false, // 不使用任何编码,因为form_data对象自带编码
            processData:false, // 告诉浏览器不要处理,直接发就行
            success:function (data) {
                alert(data)
            }
        })
    })
</script>
</body>

def upload(request):
    if request.is_ajax():
        if request.method == 'POST':
            print(request.POST)
            print(request.FILES)
            return HttpResponse('已收到文件!')
    return render(request,'upload.html')
"""
ajax传文件需要注意的事项
1.利用formdata对象 能够简单的快速传输数据 (普通键值 + 文件)
2.有几个参数
    data:formdata对象

    contentType:false
    processData:false

"""

contentType front end of the transmission data coding format

form form, submit the default encoding format of the data is urlencoded

urlencoded

  • username = admin & password = 123 which is consistent with the data format urlencoded
  • django rear end for username = admin & password = urlencoded data format 123 will automatically parse
    the results from the package to the user only request.POST request.POST correspondence information to obtain

formdat to

  • django backend will automatically parse data format type for formdata
  • But do not put request.POST, but rather to put you in request.FILES

Ajax

  • ajax submit data default encoding format is also urlencoded

Summary : Django back-end data for different encoding formats, there will be no processing mechanism and the different methods of data acquisition.

Note :

  • Front and rear end when doing data exchange must be sure to indicate that you send the data in the end is what format

  • What format you should be accurate when you tell people what format the data is

Serialization assembly

The query data is returned to the user table out of the front end, to a front end of a field of a large dictionary of the dictionary data

from django.core import serializers
    def ser(request):
    user_queryset = models.Userinfo.objects.all()
    # 传统方法:[{},{},{},{}]
    # user_list = []
    # for user_obj in user_queryset:
    #     user_list.append({
    #         'username':user_obj.username,
    #         'password':user_obj.password,
    #         'gender':user_obj.get_gender_display(),
    #     })
    res = serializers.serialize('json',user_queryset)
    print(res)
    return render(request,'ser.html',locals())

Integrated example: ajax + sweetalert

$("#b55").click(function () {
    swal({
        title: "你确定要删除吗?",
        text: "删除可就找不回来了哦!",
        type: "warning",
        showCancelButton: true,  // 是否显示取消按钮
        confirmButtonClass: "btn-danger",  // 确认按钮的样式类
        confirmButtonText: "删除",  // 确认按钮文本
        cancelButtonText: "取消",  // 取消按钮文本
        closeOnConfirm: false,  // 点击确认按钮不关闭弹框
        showLoaderOnConfirm: true  // 显示正在删除的动画效果
    },
         function () {
        var deleteId = 2;
        $.ajax({
            url: "/delete_book/",
            type: "post",
            data: {"id": deleteId},
            success: function (data) {
                if (data.code === 0) {
                    swal("删除成功!", "你可以准备跑路了!", "success");
                } else {
                    swal("删除失败", "你可以再尝试一下!", "error")
                }
            }
        })
    });
})
"""
当你是用ajax做前后端 交互的时候 
你可以考虑返回给前端一个大字典
"""
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')
        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,'sa.html',locals())

Guess you like

Origin www.cnblogs.com/dadazunzhe/p/11755968.html