Django3 web application development practice Huang Yongxiang chapter summary
Route (III) usage of route
-
Use routing in templates
-
reverse and resolve
-
Route redirection
In "proficient in Django 3 Web development 3.1 setting routing and distribution rules", it is written:
URLs. From MyDjango folder According to the routing information defined by py, the routing address of each project application (App) is given to URLs of the project application Py manages itself. This is the distribution rule of routes, which enables routes to be classified and managed according to certain rules. The working principle of the whole routing design mode is described as follows:
(1) When running the babys project, Django starts from URLs. In the babys folder Py find URLs of each project application (App) Py, and then read the URLs of each project application (App) Py defined routing information to generate a complete routing list.
(2) When a user accesses a routing address on the browser, Django will receive the user's request information.
(3) Django obtains the routing address from the current request information, matches the corresponding routing information in the routing list, and then executes the view function (or view class) pointed to by the routing information, so as to complete the whole request response process.
django's route naming name is used to name routes. Its function is to use route naming name in other functional modules such as views or templates to generate route addresses during development.
Namespace namespace can quickly locate URLs applied by a project for us Py, combined with route naming name, can quickly get URLs from the project application Py to find the specific information of a route, so that you can effectively manage the route list of the whole project.
1. Use routing in templates
Do not set namespace
# MyDjango of urls.py from django.contrib import admin from django.urls import path, include # Import Django Routing function module # urlpatterns A collection of routes representing the entire project urlpatterns = [ path('admin/', admin.site.urls), # Point to built-in Admin Routing file of background system sites.py path('', include('index.urls')), # point index Route file for urls.py ]
# index of urls.py from django.urls import path from . import views urlpatterns = [ # Add with character type, integer, and slug Route for.<Data format type: variable name>,Default character type without setting data type. path('<year>/<int:month>/<slug:day>', views.mydate, name='mydate'), path('',views.index) ]
#index of views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def mydate(request, year,month,day): return HttpResponse(str(year)+'/'+str(month)+'/'+str(day)) def index(request): return render(request,'index.html')
#templates of index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> hello word! <a href="{% url 'mydate' '2022' '01' '28' %}">View date</a> </body> </html>
Template syntax url to generate routing address
The mydate in the {% URL 'mydate', '2022', '01', '28'%} represents the route named mydate, that is, URLs of index Py has the routing of character type, integer and slug.
Set namespace
# Django of urls.py from django.contrib import admin from django.urls import path, include # Import Django Routing function module # urlpatterns A collection of routes representing the entire project urlpatterns = [ path('admin/', admin.site.urls), # Point to built-in Admin Routing file of background system sites.py path('', include('index.urls')), # point index Route file for urls.py path('', include(('index.urls', 'index'), namespace='index')), ]
#templates of index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> hello word! {# <a href="{% url 'mydate' '2022' '01' '28' %}">View date</a> #} <a href="{% url 'index:mydate' '2022' '01' '28' %}">View date</a> </body> </html>
The namespace is used in the route definition process, and the namespace should also be added to the template syntax url.
For example: 'namespace: named route name'
2. reverse and resolve
Reverse parsing: when users browse the website, Django finds the corresponding route in the route list according to the website address, finds the view function or view class from the route for processing, returns the processing result to the browser as the response content, and generates the web page content. This is irreversible. Using routing in the view is reverse parsing.
Reverse parsing is implemented by the functions reverse and resolve.
reverse generates the route address through route naming or callable view object;
resolve obtains the routing object information through the routing address.
When using these two functions, you need to pay attention to the type of parameters passed in and the data type of return value.
URLs of MyDjango py
from django.contrib import admin from django.urls import path, include # Import Django Routing function module # urlpatterns A collection of routes representing the entire project urlpatterns = [ path('admin/', admin.site.urls), # Point to built-in Admin Routing file of background system sites.py path('', include(('index.urls', 'index'), namespace='index')), ]
URLs of index py
from django.urls import path from . import views # Route named index and mydate urlpatterns = [ # Add with character type, integer, and slug Route for.<Data format type: variable name>,Default character type without setting data type. path('<year>/<int:month>/<slug:day>', views.mydate, name='mydate'), # Define the route of the home page path('',views.index,name='index') ]
Views of index py
from django.http import HttpResponse from django.shortcuts import reverse from django.urls import resolve # Create your views here. def mydate(request, year, month, day): args = ['2022', '01', '29'] result = resolve(reverse('index:mydate', args=args)) print('kwargs:', result.kwargs) print('url_name:', result.url_name) print('namespace:', result.namespace) print('view_name:', result.view_name) print('app_name:', result.app_name) return HttpResponse(str(year) + '/' + str(month) + '/' + str(day)) # index It mainly uses inverse analytic functions reverse To generate a route mydate The routing address of the. def index(request): kwargs = {'year': 2022, 'month': 2, 'day': 10} args = ['2022', '01', '29'] # use reverse Generate routing address print(reverse('index: mydate', args=args)) print(reverse('index:mydate', kwargs=kwargs)) return HttpResponse(reverse('index:mydate', args=args))
python manage.py runserver
After starting the server, the index function in views will be called
Hold down the ctrl key and click on the above views Py, you can view the source code of reverse
- viewname: represents the route name or callable view object. Generally, the route address is generated by the route name.
- Urlconf: set the urlconf module for reverse parsing. By default, the configuration file settings is used Py's ROOT_URLCONF attribute (urls.py of MyDjango folder)
- args: pass routing address variables in a list. The order and number of list elements should be consistent with the order and number of routing address variables.
- kwargs: pass the routing address variable in the form of dictionary. The key of the dictionary must correspond to the name of the routing address variable. The number of key value pairs in the dictionary is consistent with the number of variables.
- current_app: indicates the project application where the currently executing view is located. It mainly serves as a reminder, but has no substantive function.
Built in function methods:
Function method | explain |
func | View function object or view class object for routing |
args | Get route variable information in list format |
kwargs | Get the variable information of route in dictionary format |
url_name | Get route name |
app_name | Gets the second element value of the arg parameter of the item routing function include |
app_names | And app_name has the same function, but it is expressed in list format |
namespace | Get namespace |
namespaces | Consistent with the namespace function, but in list format |
view_name | Get the name of the whole route, format: namespace:name |
3. Route redirection
Redirection: HTTP protocol redirection, also known as web page Jump, is that when the browser accesses a web page, the web page does not provide response content, but automatically jumps to other web sites, and the response content is generated by other web sites.
django's web page redirection has two ways: the first way is route redirection; The second way is to customize the redirection of the view. The two redirection methods have their own advantages. The former is implemented by using django's built-in view class RedirectView, which supports HTTP GET requests by default; The latter is to set redirection in the response state of the customized view, which can enable developers to realize various development needs.
URLs of index py
from django.urls import path from . import views from django.views.generic import RedirectView urlpatterns = [ # Add with character type, integer, and slug Routing path('<year>/<int:month>/<slug:day>', views.mydate, name='mydate'), # Define the route of the home page path('', views.index, name='index'), # Set route jump path('turnTo', RedirectView.as_view(url='/'), name='turnTo'), ]
When using view class in routing, RedirectView must use as_ The view method instantiates the view, and the parameter url is used to set the route address of web page Jump, "/" represents the home page of the website (the route address named index), and then in the view of index Py defines the view functions mydate and index
index view py
from django.http import HttpResponse from django.shortcuts import redirect from django.shortcuts import reverse def mydate(request, year, month, day): return HttpResponse(str(year) + '/' + str(month) + '/' + str(day)) def index(request): print(reverse('index:turnTo')) return redirect(reverse('index:mydate', args=[2019,12,12]))
The view function index uses the redirect function redirect to redirect the web page. The function parameters can be redirected only by passing in the routing address.
The parameter settings of the template syntax url and the route definition are interrelated. The details are as follows:
- If there are variables in the routing address, the template syntax url needs to set the parameter value of the response, and the parameter values are separated by spaces.
- If there is no variable in the route address, the template syntax url only needs to set the route name without setting additional parameters.
- If the variables of the routing address are different from the parameters of the template syntax url, the browser will prompt the error message of NoReverseMatch at when accessing the web page