Video link: https://www.bilibili.com/video/BV1vK4y1o7jH
1. GET Requests and POST Requests#
Definition#
· Whether GET or POST, both are uniformly received by the
view function
, distinguishing specific request actions by judging request.method· Example:
if requests.method == 'GET': Handle business logic for GET request elif requests.method == 'POST': Handle business logic for POST request else: Other request business logic
------------------------------------------------------------------
Demonstration <Project same name folder>/views.py def test_get_post(request): if request.method == 'GET': pass elif request.method == 'POST': # Handle user submitted data pass else: pass return HttpResponse('--test get post is ok--')
GET Handling#
· GET request action is generally used to
retrieve data
from the server· Scenarios that can generate GET requests:
- Entering URL in the browser address bar and pressing enter
- <
a href
="address?parameter=value¶meter=value"> -
form form
withmethod set to get
------------------------------------------------------------------
In the GET request method, if there is data to be passed to the server, it is usually done using
query strings
【Note:do not pass sensitive data
】URL format: xxx
?parameter1=value1¶meter2=value2...
- For example: http://127.0.0.1:8000/page1`?a=100&b=200`
Server-side receives parameters
Retrieve data submitted by the client in the GET request
· Method example:
request.GET['parameter'] # QueryDict request.GET.get('parameter', 'default value') request.GET.getlist('parameter') # mypage?a=100&b=200&c=300&b=400 # request.GET=QueryDict({'a': ['100'], 'b': ['200', '400'], 'c': ['300']}) # a = request.GET['a'] # b = request.GET['b'] # Error
------------------------------------------------------------------
Demonstration http://127.0.0.1:8000/test_get_post?a=400 --test get post is ok-- Terminal <QueryDict: {'a': ['400', '200', '100']}> 100 ['400', '200', '100'] no c <Project same name folder>/urls.py urlpatterns = [ ... path('test_get_post', views.test_get_post) ] <Project same name folder>/views.py def test_get_post(request): if request.method == 'GET': print(request.GET) print(request.GET['a']) # Survey = form get Interests - checkbox print(request.GET.getlist('a')) print(request.GET.get('c', 'no c')) elif request.method == 'POST': # Handle user submitted data pass else: pass return HttpResponse('--test get post is ok--')
------------------------------------------------------------------
· Reflection: Can the previous calculator function be done with query strings?
POST Handling#
· POST request action is generally used to
submit large/private data to the server
· The client passes data to the server through forms and other POST requests, such as:
· Server-side
receives parameters
Determine if it is a POST request through request.method, such as:
if request.method == 'POST': Handle POST request data and respond else: Handle non-POST request response
------------------------------------------------------------------
Using POST method to receive client data
request.POST['parameter'] # request.POST binds QueryDict request.POST.get('parameter', '') request.POST.getlist('parameter')
Disable csrf verification, otherwise Django will reject the POST request from the client with a 403 response
------------------------------------------------------------------
Disabling csrf verification
- Disable the CsrfViewMiddleware middleware in settings.py
MIDDLEWARE = [ ... # 'django.middleware.csrf.CsrfViewMiddleware', ... ]
------------------------------------------------------------------
Demonstration
http://127.0.0.1:8000/test_get_post
post is ok Terminal uname is cpen <Project same name folder>/urls.py urlpatterns = [ ... path('test_get_post', views.test_get_post) ] <Project same name folder>/views.py POST_FORM = ''' <form method='post' action='/test_get_post'> Username: <input type='text' name='uname'> <input type='submit' value='Submit'> </form> ''' def test_get_post(request): if request.method == 'GET': return HttpResponse(POST_FORM) ...
---------------------------------------------------------------------------------------------------------------------------------
Summary
· Django handles GET requests
Using query strings - for small data transmission
· Django handles POST requests
Specifically for browser data submission
2. Django's Design Patterns and Template Layer#
MVC and MTV#
Traditional MVC#
MVC stands for
Model-View-Controller
pattern.
M Model Layer
, mainly used for encapsulating the database layer
V View Layer
, used to present results to the user (WHAT + HOW)
C Controller
, used to handle requests, retrieve data, and return results (important)Purpose:
Reduce coupling between modules (decoupling)
Django's MTV Pattern#
MTV stands for
Model-Template-View
pattern.
M Model Layer
is responsible for interacting with the database
T Template Layer
is responsible for rendering content to the browser (HOW)
V View Layer
is the core, responsible for receiving requests, retrieving data, and returning results (WHAT)Purpose:
Reduce coupling between modules (decoupling)
---------------------------------------------------------------------------------------------------------------------------------
Template Layer#
What is a Template#
A template is an
html page
that can dynamically change based ondictionary
dataTemplates can
dynamically generate corresponding HTML pages
based on the dictionary data passed in the view
Template Configuration#
Create a template folder
<Project Name>/templates
In
settings.py
, configure theTEMPLATES
option 1. BACKEND: Specify the template engine
2.
DIRS
: Template search directories (can be one or more) 3. APP_DIRS: Whether to search for template files in the templates folder of the application
4. OPTIONS: Options related to templates
· The part that needs to be modified in the configuration
Set DIRS -
'DIRS': [os.path.join(BASE_DIR, 'templates')],
------------------------------------------------------------------
Demonstration
<Project same name folder>/settings.py TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], ...
Template Loading Methods#
Option 1 - Load the template through loader and respond via HttpResponse (Characteristics: cumbersome)
In the view function:
from django.template import loader # 1. Load the template through loader t = loader.get_template("template filename") # 2. Convert t to HTML string html = t.render(dictionary data) # 3. Return the converted string content to the browser using the response object return HttpResponse(html)
--------------------------------------------------------------------------------------
Demonstration
http://127.0.0.1:8000/test_html
<Project same name folder>/urls.py urlpatterns = [ ... path('test_html', views.test_html) ] <Project same name folder>/views.py def test_html(request): from django.template import loader t = loader.get_template('test_html.html') html = t.render() return HttpResponse(html) <Project folder>/templates/test_html.html <h3>I am from the template layer~~~~</h3>
---------------------------------------------------------------------------------------------------------------------------------
Option 2 - Directly load and respond to the template using render() (Characteristics: convenient, widely used)
In the view function:
from django.shortcuts import render return render(request, 'template filename', dictionary data)
--------------------------------------------------------------------------------------
Demonstration
http://127.0.0.1:8000/test_html
<Project same name folder>/views.py def test_html(request): # Option 2 from django.shortcuts import render return render(request, 'test_html.html')
Interaction Between View Layer and Template Layer#
- In the view function, Python
variables
can be encapsulated in a dictionary and passed to the templateExample:
def xxx_view(request):
dic = {
"variable1": "value1",
"variable2": "value2",
}
return render(request, 'xxx.html',dic
)
In the template, we can use {{ variable name }} syntax to call the variables passed from the view
--------------------------------------------------------------------------------------
Demonstration
http://127.0.0.1:8000/test_html
<Project same name folder>/urls.py urlpatterns = [ ... path('test_html', views.test_html) ] <Project same name folder>/views.py def test_html(request): from django.shortcuts import render dic = {'username': 'peng', 'age': 23} return render(request, 'test_html.html', dic) <Project folder>/templates/test_html.html <h3>{{ username }} is from the template layer~~~~</h3>