Introduction to views in Django

I. Overview

1. Function

The view accepts web requests and responds to web requests

2. Essence

Views are functions in Python

3. Response type

  1. Web page
    1. Redirect
    2. Error view: 404 error, 500 error
  2. JSON data

4. Response process

  1. The user enters the URL in the browser
  2. Django gets the URL information, removes the IP address and port number
  3. Match the URL configuration one by one,
    1. If the match is successful, execute the corresponding view function
    2. If the match fails, a 404 error is reported
  4. The view manager finds the corresponding view to execute, and returns the result to the browser

Two, URL configuration

1. Configuration process

  1. Specify the root URL configuration file in
    \Django\MyDjango\project\project\settings.py
ROOT_URLCONF = 'project.urls'
  1. \Django\MyDjango\project\project\urls.py file, urlpatterns is a list of URL instances, and the URL object is passed in
urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^',include('MyApp.urls')),
]
1. URL对象包括:正则表达式,视图名称,名称
  1. Precautions for URL matching regular
    1. If you need to get a value from the URL, you need to add parentheses to the regularity of the value
    2. No need to add a backslash to match the regular start URL, because backslashes have been added in the \Django\MyDjango\project\project\urls.py file or \Django\MyDjango\project\project\settings.py file
    3. You need to add r outside the regular expression to indicate that the string is not escaped
    4. For example: \Django\MyDjango\project\project\settings.py

2. Introduce other URL configuration

  1. Create urls.py in the application, define the URL configuration of this application, and use the include() method in the project urls.py file
  2. Sample code
# \Django\MyDjango\project\project\urls.py 文件配置
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^',include('MyApp.urls',namespace="MyApp")),
]

# \Django\MyDjango\project\MyApp\urls.py 文件配置
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$',views.index),
    url(r'^(\d+)/(\d+)$',views.detail),
    url(r"^Grades/$",views.Grades)
]

3. Reverse parsing of URL

  1. Overview: If hard-coded links are used in views and templates, the link address will be dynamically generated when the URL configuration changes
  2. Solution: When using the link, the URL address is dynamically generated through the name configured by the URL
  3. Role: Use URL template

Third, the view function

1. Define the view

  1. Essence: is a Python function
  2. View parameters
    1. An instance of HTTPRequest
    2. Parameters obtained through regular expressions
  3. Location: defined in \Django\MyDjango\project\MyApp\views.py

2. Error View

  1. 404 views
    1. Return when the page is not found (URL matching is not successful)
    2. Definition path: \Django\MyDjango\project\templates\404.html
    3. Definition content
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>404页面</title>
</head>
<body>
    <h1>页面丢失</h1>
    <h2>{
    
    {
    
    request__path}}</h2> # 导致错误的网址
</body>
</html>
4. 配置settings.py
# DEBUG为True,不会调用404.html页面
DEBUG = False
# 允许访问的host
ALLOWED_HOSTS = ["*"]
5. 
  1. 500 view: An error occurred in the view code (server code)
  2. 400 view: the error occurred in the operation of the client

Fourth, the HttpRequest object

1 Overview

  1. After the server receives the http request, Django will create an HttpRequest object based on the message. The first parameter of the view is the HttpRequest object, which is then passed to the view when calling the view.

2. Properties

  1. path
    The full path of the request (does not include the domain name and port number)
  2. method
    request method, get, post
  3. Encoding
    represents the encoding method of the data submitted by the browser, generally utf-8
  4. GET
    dictionary-like object, contains all the parameters of the get request
  5. POST is
    a dictionary-like object that contains all the parameters of the post request
  6. FILES is
    a dictionary-like object that contains all uploaded files
  7. COOKIES
    dictionary, contains all cookies
  8. SESSION
    dictionary-like object, representing the current session

3. Method

  1. is_ajax()
    returns True if it is initiated via XMLHttpRequest

4. QueryDict Object

  1. Overview: GET and POST in the request object belong to the QueryDict object
  2. method
    1. get() Function: Get the value according to the key, only one value can be obtained
    2. get() example: www.baidu.com/abc?a=1&b=2&c=3
    3. getlist() Function: return the value of the key in the form of a list, multiple values ​​can be obtained
    4. getlist() example: www.baidu.com/abc?a=1&a=2&c=3

5. GET attributes

1. Get a value for an attribute

  1. \Django\MyDjango\project\MyApp\views.py file add the following code
# 获取GET传递的数据
def GetOneAttribles(request):
    AttributeA = request.GET.get("a")
    AttributeB = request.GET.get("b")
    AttributeC = request.GET.get("c")
    Sum = int(AttributeA) + int(AttributeB) + int(AttributeC)
    #return HttpResponse(AttributeA + "  " + AttributeB + "  " + AttributeC)
    return HttpResponse(Sum)
  1. Configure the url information in the APP
  2. Visit address: http://127.0.0.1:8000/GetOneAttribles/?a=1&b=2&c=3
    Insert picture description here

2. Get multiple values ​​for one attribute

  1. \Django\MyDjango\project\MyApp\views.py file add the following code
# 获取GET传递的数据
def GetMultipleAttribles(request):
    AttributeAList = request.GET.getlist("a")
    a1 = AttributeAList[0]
    a2 = AttributeAList[1]
    AttributeC = request.GET.get("c")
    return HttpResponse(a1 + "" + a2 + "" + AttributeC)
  1. Configure the url information in the APP
  2. Visit address: http://127.0.0.1:8000/GetOneAttribles/?a=1&a=3&c=3
    Insert picture description here

6. POST attributes

  1. \Django\MyDjango\project\MyApp\urls.py added routing information
url(r"^ShowRegist/$",views.ShowRegist),
url(r"^ShowRegist/Regist/$", views.Regist),
  1. \Django\MyDjango\project\MyApp\views.py is adding request methods
# 获取POST传递的值
def ShowRegist(request):
    return render(request,"MyApp/Regist.html")

def Regist(request):
    Name = request.POST.get("name")
    Gender = request.POST.get("gender")
    Age = request.POST.get("age")
    Hobby = request.POST.getlist("hobby")
    print("Name:%s,Gender:%s,Age:%s,Hobby:%s"%(Name,Gender,Age,Hobby))
    return HttpResponse("POST请求成功")
  1. Add a registration page to the template
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
    <form action="Regist/" method="post">
        姓名:<input type="text" name="name" value=""/>
        <hr/>
        性别:<input type="radio" name="gender" value="1"/><input type="radio" name="gender" value="0"/><hr/>
        年龄:<input type="text" name="age" value=""/>
        <hr/>
        爱好:<input type="checkbox" name="hobby" value="power"/>权利<input type="checkbox" name="hobby" value="money"/>金钱<input type="checkbox" name="hobby" value="girl"/>美女
        <hr/>
        <input type="submit" value="注册">
    </form>
</body>
</html>
  1. \Django\MyDjango\project\project\settings.py middleware comment CSRF line code
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  1. The browser visits the page to fill in the form, and click the register button to print out the registration information, and then you can use the model object to connect to the database to save
    Insert picture description here
    Insert picture description here

Five, HttpResponse object

1 Overview

  1. Role: return data to the browser
  2. The HttpRequest object is created by Django, and the HttpResponse object is created by the programmer

2. Return to usage

1. Do not call the template, return the data directly

  1. code show as below
def Regist(request):
    Name = request.POST.get("name")
    Gender = request.POST.get("gender")
    Age = request.POST.get("age")
    Hobby = request.POST.getlist("hobby")
    print("Name:%s,Gender:%s,Age:%s,Hobby:%s"%(Name,Gender,Age,Hobby))
    return HttpResponse("POST请求成功")
  1. The effect is as follows
    Insert picture description here

2. Call the template, use the render() method

  1. 原型:render(request,templateName[,context])
  2. Role: Combine data and templates to return a complete HTML page
  3. parameter
    1. request: request body object
    2. templateName: template path
    3. Pass to the data that needs to be rendered on the template
  4. Example
# 查询年龄大于30或小于20的学生列表
from django.db.models import Q
def GetAgeGTThrityOrLTTwentyOfStudent(request):
    StudentsList = Student.StudentObj2.filter(Q(studentAge__gt=30)|Q(studentAge__lt=20))
    return render(request, 'MyApp/students.html', {
    
    "studentsHtml": StudentsList})

3. Properties

1. content: indicates the return content

2. charset: encoding format

3. status_code: response status code, 200, 304, 404

4. content-type: Specify the MIME type of the output

4. Method

1. init: Make the page content instantiate the HttpResponse object

2. write(content): write in the form of a file

3. flush(): output the buffer in the form of a file

4. set_cookie(key,value="",max_age=None,exprise=None):设置cookie

5. delete_cookie(key): delete the cookie, if you delete a non-existent key, nothing happens

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/114213999