choices field, mtv and mvc models, ajax basic syntax, sweetalert popup plugin, custom pager

Supplement: emailField is actually charField

    models中所有的字段类型都没有实际的约束作用
    但是虽然写在models中没有限制作用,但是它们对于校验性组件
    是非常有用的

Check Line Components

1689626-20190926155953442-1428221614.png

1. Choices parameter

The choices parameter is a parameter commonly used in models, in this case it is the parameter in IntegerField().

1 Introduction : How does gender exist? Usually stored in numbers . Figure 1

# 图1
username    gender
jason       1

Others that require "things that require the choices parameter": Figure 2

# 图2 
用户性别
用户学历
工作状态
客户来源
是否结婚

This case uses Django's default database sqlite:

Operation method:

The sqlite database can be used directly! make migration and migrate

2Django test environment (review)

import os
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day57.settings")
    import django
    django.setup()
    from app01 import models
    
    #下面写要测试的内容,比如:
    user_obj = models.User.objects.filter(pk=7).first()
    # print(user_obj.gender)
    print(user_obj.get_gender_display())
    """
    只要是choices字段 在获取数字对应的注释 固定语法
    get_choices字段名_display()
    """

4choices writing: take age as an example

4.1models storage
#models存

choices =((1,'男'),(2,'女'),(3,'保密'))
gender = models.InteferField(choices = choices)
# 现在,存到数据库里是数字
4.2 test take
# 固定格式
get_字段名_display()
# 比如
user_obj = models.User.objects.filter(pk=7).first()
user_obj.get_gender_display()

# 存没有罗列迟来的数字
 不会报错 还是展示数字

There is no corresponding relationship to take out the number!

Gentlemen love fortune, in a proper way

There is no free lunch

2. MTV and MVC model

To understand the knowledge points is to abbreviate the English words. All web frameworks are MVC models .

The django framework calls itself an MTV framework: M:models; T:templates;V:views

MVC: M: models; V: views; C: controller controller (urls)

Note: There may be matching errors in the regular expression of the url, so write the regular expression more accurately

Three, ajax (key)

Specific: Asynchronous commit partial refresh

a标签href属性              GET请求
浏览器窗口输入url           GET请求
form表单                  GET/POST
ajax                      GET/POST

Ajax is a new way to send get and post requests. And can send json format (form form does not support json format)

​ First of all, the technology of ajax is in js, but the native js operation of ajax is cumbersome. In order to improve efficiency, we directly use the jQuery packaged version of ajax

The biggest advantage of AJAX is that you can exchange data with the server and update part of the web page content without reloading the entire page.
(This feature gives the user the feeling that the request and response process is completed unknowingly)

case snooping ajax

Reminder: post request must annotate the content of setigns

def index(request):
    # print(request.is_ajax())  # 用来判断当前请求方式是否是ajax请求,打开网页默认是GET请求,走index.html
    if request.is_ajax():
        if request.method == 'POST': # ajax请求有两种请求方法
            # print(request.POST)<QueryDict: {'i1': ['213'], 'i2': ['34']}>,ajax请求提交的数据全部在request.POST中
            i1 = request.POST.get('i1')
            i2 = request.POST.get('i2')
            # 后端获取的前端数据 都是字符串格式
            res = int(i1) + int(i2)
            return HttpResponse(res) #三剑客此时都会返回到html里
    return render(request,'index.html')

#前端
    $('#b1').on('click',function () {
        alert(123)
        // 点击按钮 朝后端发送post请求
        $.ajax({
            url:'',  // 控制发送给谁 不写就是朝当前地址提交
            type:'post',  // 发送方式是post请求
            data:{'i1':$('#i1').val(),'i2':$('#i2').val()},  // 发送的数据
            success:function (data) {  // data形参就是后端返回的异步提交的结果,通常是一个字典
                // data自动转成自定义对象,可以使用点点点的方法,
                // if (data.code ==1000){
                    逻辑
                }
                // 将后端计算好的结果 通过DOM操作 渲染到第三个input矿中
                $('#i3').val(data)
            }

        })

Four, contentType front-end and back-end transmission data encoding format

4.1 Front-end and back-end transmission data encoding format

1.urlencoded》》》name=SDF&password=FDS
2.formdata》》》看不到编码格式;传文件也支持传普通键值(name=jason&pwd=123&hobby=read)
3.application/json  # json格式数据(form表单是无法发送

​ 4.1.1 form form , the default encoding format is urlencoded

​ form form can upload files

How does the django backend handle different encoding formats?

只要是符合urlencoded编码格式  都会被后端自动获取并解析放到request.POST中
如果是符合formdata那么文件会自动被解析放到request.FILES中
如果是json格式 后端默认不解析 以二进制的形式就放在request.body你可以自己手动处理即可

1689626-20190926160023586-805673680.png

​4.1.3 ajax submission data : json and files

The default data submission method of ajax is also urlencoded, and the data sent by ajax in json format is placed in request.body

print(,request.body)b'{"name":"wx","password":"123"}'

JSON format ajax needs to manually process JSON format data

$('#b1').on('click',function () {
    alert(123)
    // 点击按钮 朝后端发送post请求
    $.ajax({
        url:'',  // 控制发送给谁 不写就是朝当前地址提交
        type:'post',  // 发送方式是post请求
        data:JSON.stringify({'username':'jason','password':123}),  // 发送的数据
        // 告诉后端你这次的数据是json格式
        contentType:'application/json',  // 
        success:function (data) {  // data形参用来接收异步提交的结果
                                 alert(data)
                                 // 将后端计算好的结果 通过DOM操作 渲染到第三个input矿中
                                 $('#i3').val(data)
                                }
    })
    // {)

ajax file transfer:

​ Required: for

 // ajax传输文件
                $('#b1').on('click',function () {
                    // ajax传输文件 建议使用内置对象formdata
                    var formData = new FormData();  // 既可以传普通的键值对 也可以传文件
                    // 添加普通键值
                    formData.append('username','jason');
                    formData.append('password','123');
                    // 传文件
                    // 如何获取文件标签所存储的文件对象?  固定语法
                    // 1.先用jQery查找到存储文件的input标签
                    // 2.将jQuery对象转成原生js对象
                    // 3.利用原生js对象的方法 .files[0]获取到标签内部存储的文件对象
                    // 4.一定要指定两个参数都为false
                    formData.append('my_file',$('#d1')[0].files[0]);
                    $.ajax({
                        url:'',  // 控制发送给谁 不写就是朝当前地址提交
                        type:'post',  // 发送方式是post请求
                        data:formData, // 发送的数据

                        // ajax发送文件需要指定两个额外的参数
                        processData:false,  // 告诉前端不要处理数据
                        contentType:false,  // 不适用任何编码  因为formdata对象自身自带编码 django后端也能够识别formdata对象
                        success:function (data) {  // data形参用来接收异步提交的结果
                            {#alert(data)#}
                            // 将后端计算好的结果 通过DOM操作 渲染到第三个input矿中
                            $('#i3').val(data)
                        }

                    })
                })

5. Serialization component: serializers: Display database data and rendering dictionary on the front-end page

Requirement: Organize all data into a json-compliant dictionary and send it to the front-end page

def reg(request):
    user_list = models.User.objects.all()
    user_l=[]
    for i in user_list:
                               user_l.append(json.dumps({'uername':i.name,'age':i.age,'gender':i.get_gender_display()}))
    return render(request,'index.html',locals())

These code serializers do it for you. And he integrates more data than you

def reg(request):
    user_list = models.User.objects.all()
    res = serializers.serialize('json',user_list)
    return render(request,'index.html',locals())
# .而且他整合的数据比你多
[{"model": "app01.user", 
  "pk": 1,
  "fields": {"name": "\u5434\u9521", 
             "age": 23, "gender": 1}}, 
 {"model": "app01.user",
  "pk": 2, 
  "fields": {"name": "\u738b\u5927\u9524", "age": 18, "gender": 2}},
 {"model": "app01.user",
  "pk": 3, 
  "fields": {"name": "\u9f50\u5929\u5927\u5723", "age": 99, "gender": 3}}]

06 Ajax combined with sweetalert plugin

sweetalert makes popovers a little nicer. Need to download: we just need to use the dist folder inside

1689626-20190926160100893-663907926.png

Bulk insert data 1.:

1. 这种插入速度非常慢
for i in range(1000):
   models.Book.objects.create(title='第%s本书'%i)
2.
l = []
for i in range(10000):
    l.append(models.Book(title='第%s本书'%i))
    models.Book.objects.bulk_create(l)  # 批量插入数据
page display of user data

Note: {{user.get_gender_display}} in the html file does not need to add parentheses here, it will add

custom pager

You don't need to write anything, you just need to know the idea

Condition: quertest supports slicing

1689626-20190926160120887-1172172184.png

The object when the front-end for loop loops! , cannot {% for i inrange(10)%}, there is no range parameter in the front end

book_list = models.Book.objects.all()
current_page = request.GET.get("page",1)
all_count = book_list.count()
page_obj=Pagination(current_page=current_page,all_count=all_count,per_page_num=10,pager_count=5)
page_queryset = book_list[page_obj.start:page_obj.end]
前端代码
{% for book in page_queryset %}
<p>{
    
    { book.title }}</p>
{% endfor %}
{
    
    { page_obj.page_html|safe }}

Front-end import file

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
{% load static %}
<link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'dist/sweetalert.min.js' %}"></script>

Reprinted in: https://www.cnblogs.com/ZDQ1/p/11592357.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326559566&siteId=291194637