django twenty-eight-one of the form submission methods: get request

1. The purpose of writing this blog

Record the form submission method and how to use the get request combined with several common scenarios. In the future, even if I haven't used it for a long time and won't use the get request, I can quickly review it by viewing this blog;

Involving the use of form submission methods: submit data from an html page to the server through any form submission method. After receiving the data, the server judges the submitted data, and then makes a corresponding response and returns to the specified html page (such a The whole process is the knowledge points related to the form, which will involve the interaction of data);

The three relevant scenarios are:

  • Scenario 1: After obtaining the front-end request, without processing the requested data, a specific result will be returned uniformly;
  • Scenario 2: After obtaining the front-end request, process the request data (the request data does not involve comparison and verification with the data table data), and the corresponding specific results will be returned for different processing results;
  • Scenario 3: After obtaining the front-end request, process the requested data (the request data involves comparison and verification with the data in the data table), and the corresponding specific results will be returned for different processing results;

We only need to know how to use these three scene instances, and we don't need to learn other scene instances;

There are four types of form submission methods: post, get, delete, put, but 99% of the mainstream ones are post and get, especially post is more commonly used than get. For example, an e-commerce company’s ecrp open platform has 360 interfaces and these 360 The form submission method of this interface is all post, so we don't need to learn in depth for delete and put, we only need to have this concept;

The actual implementation of each scenario can be viewed separately in the following complete operation process;

 

Second, the actual complete operation process of the three scenarios

1. [Scenario 1: After obtaining the front-end request, without processing the request data, it will return a specific result uniformly;] the complete operation process

1.1. The first step: Add a new [qq_test.html] in the project [helloworld/hello/templates]

detail:

①. The form is implemented by the [<form>] tag in the html file. A complete form contains four parts: submission address, request method, element controls, and submit button. The functions of the four parts are as follows:

  • Attribute action submission address (set which url the data submitted by the user is received and processed)
  • Attribute method request method (mainstream commonly used request methods include get and post)
  • Label input element control (input text information)
  • Property submit submit button (trigger submission action/trigger access to the url that receives the request)

②. In the html file, each tag such as [<form>] can be understood as a class; the attributes in each tag, such as the attribute action in the tag <form>, can be understood as a method (in python language , There are concepts of classes and methods);

③. In the html file, click on a certain tag such as [<form>], or click on a certain attribute such as [action], you can jump to the page where the source code is located (html itself is also a computer language, we just need how to use No need to understand the source code at the initial stage);

④. Knowledge points about the value of the attribute action:

  • If the value is an empty string, it means: the requested data is submitted to the current html page;
  • If the value is a value that contains the parameter value corresponding to the parameter name in the url matching rule, for example, the value is ["{% url'urlName_of_qq_result' %}"], which means: the request data is submitted to the parameter value corresponding to the parameter name [UrlName_of_qq_result] URL matching rules;

Related code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>测试你的QQ号</title>

</head>

<body>

<p>请输入你的QQ号</p>



<form action="{% url 'urlName_of_qq_result' %}" method="get">

    qq: <input type="text" name="q"> <br>

    <br>

    <input type="submit" value="提交">

</form>



</body>

</html>

 

1.2. Step 2: Add two view functions to the project [helloworld/hello/views.py]

def qq_test1(request):

    return render(request,'qq_test.html')



def qq_result1(request):

    return HttpResponse("这个qq的数据提交成功了!")

1.3. Step 3: Add two URL matching rules in the project [helloworld/helloworld/urls.py]

    url(r"^qq_test001/$",views.qq_test1),

    url(r"^qq_result001/$",views.qq_result1,name="urlName_of_qq_result"),

1.4. Step 4: Restart the service

1.5. Step 5: Visit the url on any browser [ http://127.0.0.1:8000/qq_test001/ ]

1.6. Step 6: Enter any QQ number in the submit field [qq] on the page corresponding to the url [ http://127.0.0.1:8000/qq_test001/ ] and click the submit button

 

2. [Scenario 2: After obtaining the front-end request, process the requested data (the request data does not involve comparison and verification with the data in the data table), and the different processing results will return the corresponding specific results;] the complete operation process

2.1. The first step: modify the view function [qq_result1] in the project [helloworld/hello/views.py]

detail:

①. [request.GET] can be regarded as a dictionary, the values ​​passed by the GET method will be stored in it, and you can use request.GET['key_name'] to get the value. But when the key value does not exist, this error will be reported: "MultiValueDictKeyError";

②. In order to avoid an error when the key value does not exist, we can use another way of writing: request.GET.get("q",None);

③'key_name' in.request.GET['key_name']: refers to the attribute name of the name attribute in each input tag in the form tag in the html page;

④.key value: refers to the value of the name attribute in each input tag in the form tag in the html page;

def qq_result1(request):

    # return HttpResponse("这个qq的数据提交成功了!")



    if request.method == 'GET':

        # 获取前端页面提交的数据

        qq_value = request.GET.get("q",None) # 这个写法比较稳

        # qq_value = request.GET["q"]    # 这个写法也可以

        result = ""

        try:

            if int(qq_value)%2 ==0:

                res = "这个qq号是偶数"

            else:

                res = "这个qq号是奇数"

        except:

            res = "请输入正确的qq号"



        return  HttpResponse("测试结果:%s"%res)

2.2. Step 2: Restart the service

2.3. Step 3: Visit the url on any browser【http://0.0.0.0:8000/qq_test001/

2.4. Step 4: Enter any qq number in the submit field [qq] on the page corresponding to the url [ http://0.0.0.0:8000/qq_test001/ ] and click the submit button

 

3. [Scenario Three: After obtaining the front-end request, process the request data (request data involves comparison and verification with the data in the data table), and return corresponding specific results for different processing results;] the complete operation process

3.1 The first step: Add a new [animal_search_html.html] in the project [helloworld/hello/templates/animal]


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>查询符合年龄的所有动物的动物名</title>

</head>

<body>

<form action="" method="get">

    输入动物的年龄: <input type="text" name="age_of_animal"> <br>



    <br>

    <input type="submit" value="提交">

</form>



<p>符合年龄的所有动物的动物名:{
   
   {result}} </p>

</body>

</html>

 

3.2. Step 2: Add a view function to the project [helloworld/hello/animalViews.py]


#!/usr/bin/python

# -*- coding:utf-8 -*-



"""""""""""""""""""""""""""""""""

@file: animalViews.py

@author: lucas

@createTime: 2021/3/9 4:56 下午

@Function: 存储数据表animal的所有视图操作

"""""""""""""""""""""""""""""""""

from django.shortcuts import render



from hello.models import Animal





def animal_search(request):

    result_of_return = ""

    if request.method == 'GET':

        # 获取提交的数据

        try:

            age = request.GET.get("age_of_annimal", None)

            res = Animal.objects.filter(age=age).values()

            if len(res) == 0:

                # result_of_return = ""  # 可用这行代码替代

                pass

            else:

                for i in res:

                    result_of_return = result_of_return + i["name"] + ';'

        except:

            result_of_return = "查询的值只能为自然数"

        print(result_of_return)

        return render(request, 'annimal/animal_search.html', {"result": result_of_return})

 

3.3. Step 3: Add a url matching rule in the project [helloworld/helloworld/urls.py]

    #这部分是针对数据表animal的所有url匹配规则的汇总=====================================================



     url(r"^animal_search_001/$",animalViews.animal_search),

    #这部分是针对数据表animal的所有url匹配规则的汇总=====================================================

3.4. Step 4: Restart the service

3.5. Step 5: Visit the url on any browser [ http://127.0.0.1:8000/animal_search_001/ ]

3.6. Step 6: Enter any natural value in the submission field [Enter the age of the animal] on the page corresponding to the url [ http://127.0.0.1:8000/animal_search_001/ ] and click the submit button

 

 

 

 

Guess you like

Origin blog.csdn.net/LYX_WIN/article/details/114691101