🍖 Routing layer of Django framework ⭐


1、 Route matching in routing layer

1. What is routing

  • Routing can be regarded as the address following IP and port


2. URL () method

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login_func),
    url(r'^register/$', views.register_func),
  • url( )The first parameter of the method is actuallyregular expression Once the first parameter matches the content, it ends the matching directly and calls the corresponding view function

3. Routing matching considerations

  • There is no need to add a backslash before the route"/", because each URL comes with it
  • It is recommended to add native characters before regular expressions"r"
  • Each parameter captured by a regular match and grouped is passed to the view function as a normal Python string
  • If the end of the route does not"/"When the regular matching mechanism fails to match the desired content for the first time, it will add one after the matching character"/", and then Django internal redirection matches once


4. Cancel adding slash automatically"/"

  • The route is tested above, but not added later"/"There were two matches
  • Automatic addition of slashes can be cancelled
#Setting.py file
APPEND_ Slash = false # default true automatically adds slashes
  • After setting, if you do not add a slash, you cannot access the resource


It is recommended to add automatically

2、 Group name matching

1. Anonymous group

  • The first parameter in the URL () method is regular expression grouping: add a parenthesis before and after the regular expression

  • The content matched by the regular expression in brackets will be passed to the following view function as a positional parameter

url(r'^login/$', views.login_func)

#Anonymous group 
url(r'^login/(\d+)/$', views.login_func)
#View function
def login_func(request,*args):
    return Httpresponse(args)

2. Famous group

  • Define a name for the content captured by grouping regular expressions
  • The content matched by the regular expression in brackets will be passed to the following view function as a keyword parameter
url(r'^login/$', views.login_func)

#Famous group
url(r'^login/(?P\d+)/$', views.login_func)
#View function
def login_func(request,**kwargs):
    return Httpresponse(args)

3. Can nameless names be used in combination

  • NoCombined use
url(r'^login/(\d+)/(?P\d+)/$', views.login_func)
#The official said that it can't be mixed. Mixed use can only get the values captured by famous groups
#As long as they are not mixed, the name group and nameless group support multiple parameters of the same type
  • It can be reused individually
url(r'^login/(\d+)/(\d+)/$', views.login_func)
url(r'^login/(?P\d+)/(?P\d+)/$', views.login_func)

3、 Reverse analysis

1. What is reverse parsing

  • Reverse parsing is to get a result through some methods, which can directly access the corresponding URL and trigger the view function

2. The role of reverse analysis

  • When using a Django project, we often need to embed a URL into the generated content. If these URLs are fixed, the scalability is poor, and the expired URLs will be generated to a certain extent
  • Using reverse parsing is to dynamically parse the connection address on the HTML interface when the route changes frequently

3. How to use reverse parsing

  • Add an alias to the corresponding relationship between route and view function (the name is specified by yourself, as long as there is no conflict)
#Routing layer
url(r'^login/$', views.login_func,name='login_name')
  • According to the alias, a result can be dynamically parsed, which can directly access the corresponding route
#Use in front end (template layer)

#Used in the back end (view layer)
from django.shortcuts import reverse
url = reverse('login_name')

PS: the alias can also be written directly in brackets

4. Reverse parsing of anonymous group

  • Routing layer configuration
url(r'^login/(\d+)/', views.login_func,name='login_name')
  • View layer configuration
from shortcuts import reverse
url = reverse('login_ Name ', args = (1,))? Give me a number
  • Template layer
Log in and give me a number

The number obtained by packet matching in the routing layer is not written like this. In general, it is the primary key value of the data. We can get the primary key of the data, and then locate the data object, so that we can edit and delete the data

#Routing layer
url(r'^login/(\d+)/', views.login_func,name='login_name')

#View layer
def edit(request,edit_id):
#Template layer
{% for user_obj in user_list %}

5. Reverse parsing of named groups

  • Routing layer configuration
url(r'^login/(?P\d+)/', views.login_func,name='login_name')
  • View layer configuration
from shortcuts import reverse
url = reverse('login_ Name ', kwargs = (ID: 111)) # just give me a number
url= =
reverse('login_ Name ', args = (111,)) #
  • Template layer configuration
Log in and give me a number
You can also log in like this

From the above view layer and template layer of the second way of writing can be seen: nameless have nameYou can use a form of reverse parsing: YesunknownReverse analysis

4、 Routing distribution

1. Introduction to routing distribution

Django focuses on developing applications. When a Django project is very large, all the mapping relationships between routing and view functions are written in one fileurls.pyIt’s obviously redundant and unmanageable

In fact, every application in Django can have its ownUrls.py, static folder, Templates folderBased on the above characteristics, using Django to doGroup developmentIt’s very simple

Everyone just needs to write their own applications. Finally, the team leader summarizes them into an empty Django project, and then uses routing distribution to associate multiple applications together

  • After routing distribution, the total route does not interfere with the direct correspondence between the route and the view function, but does a distribution process to identify the current routeurlThe application to which it belongs will be distributed directly to the corresponding application for processing,And it doesn’t matter to apply duplicate routing names

2. Routing distribution settings

  • Total routing file: urls.py

Note: the total route cannot be added after the regular"$"Otherwise, it will be over as soon as you get to app01

from django.contrib import admin
from django.urls import path,re_path,include

#Method 1: complex writing
from app01 import urls as app01_ulrs
from app02 import urls as app02_ulrs
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^app01/', include(app01_ulrs)),
    re_path(r'^app02/', include(app02_ulrs)),
    re_path(r'^app03/', include(app03_ulrs))

#Mode 2: Advanced Writing
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^app01/', include('app01.ulrs')),
    re_path(r'^app02/', include('app02.ulrs')),
    re_path(r'^app03/', include('app03.ulrs'))
  • Each application route (sub route) file: urls.py
from django.contrib import admin
from django.urls import path,re_path
From [app name] import views

urlpatterns = [

5、 Name space

1. Why use a namespace

When multiple applications set the same alias, the previous route will be covered by the following route during reverse resolution, so the view function corresponding to the previous route cannot be triggered. Under normal circumstances, reverse resolution cannot automatically identify the prefix. In order to avoid this error, the namespace is introduced

2. Application name space and instance name space

  • name_ App: application namespace: usually specified in urls.py file of application app (no error report is specified after django2 version)
# app01
app_ Name ='app01 'ා application namespace
urlpatterns = [
  • Namespace: instance namespace: usually specified in the total routing file

2. Solution 1: use a namespace

  • Total route setting: urls.py file
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^app01/', include('app01.ulrs',namespace='app01')),
    re_path(r'^app02/', include('app02.ulrs',namespace='app02')),
    re_path(r'^app03/', include('app03.ulrs',namespace='app03'))
  • Sub route setting: urls.py file
# app01
urlpatterns = [

# app02
urlpatterns = [

# app03
urlpatterns = [
  • View file: views.py file
# app01
from django.shortcuts import reverse
def home_func(request):
    res = reverse('app01:home_name')
    return HttpResponse(res)  # /app01/home/

# app02
from django.shortcuts import reverse
def home_func(request):
    res = reverse('app02:home_name')
    return HttpResponse(res)  # /app02/home/

# app03
from django.shortcuts import reverse
def home_func(request):
    res = reverse('app03:home_name')
    return HttpResponse(res)  # /app03/home/
  • Template layer file

3. Solution 2: add prefix manually

# app01
urlpatterns = [

# app02
urlpatterns = [

# app03
urlpatterns = [

6、 Pseudo static

1. Static page

  • Written page, data has been fixed dead, will not change

2. Dynamic page

  • Page content can change with time, environment, or database

3. Pseudo static page

  • The purpose is to better be included by the search engine and SEO query probability, and through certain rules, the address of the dynamic page is converted to the address ending with HTM or HTML. It looks static, but in fact it is still a dynamic page
  • For example, the end of the blog address is.htmlBut we can modify the content of the article


PS: no matter how to optimize it, it can’t be compared with adding money

4. Modify the matching rules to achieve pseudo-static

  • Routing layer file
urlpatterns = [

7、 Django version differences

Django 1.xVersion and2.x3.xThe difference between versions

1. Route matching method in route layer

  • 1.xIs used inurl( )Method, the first argument is a regular expression
  • 2.xAnd3.xIs used inpath( )Method, the first parameter does not support regular expressions, so you can match whatever you want

If you want to be in the2.xand3.xIf you use a regular expression in the first parameter in, you need to import itre_pathmethod

from django.urls import path,re_path

re_pathEquivalent to1.xInurlmethod

2. Five common converters in path method

STR: matches non empty strings other than the path separator (/), which is the default form
Int: matches a positive integer containing 0.
Slug: matches a string of letters, numbers, horizontal bars, and underscores.
UUID: match the formatted UUID, such as 075194d3-6885-417e-a8a8-6c931e272f00.
Path: matches any non empty string, including the path separator (/) (cannot use? (No.)

3. Custom converter

class MonthConverter:
    Regex = '\ D {2}' # attribute name must be regex

    def to_python(self, value):
    return int(value)

    def to_url(self, value):
    Return value # the matching regex is two numbers, and the returned result must also be two numbers

from django.urls import path,register_converter
from app01.path_converts import MonthConverter

#Register converter

from app01 import views
urlpatterns = [
    path('articles////', views.article_detail, name='date_time'),


8、 Install local virtual environment

1. Why use local virtual environment

  • In the process of time development, we will provide different environments for different projects
  • Whatever is used in the project will be installed, and those that cannot be used will not be installed
  • Different project interpreter environments are different

2. What is requirements.txt

  • Using projects written by others requires a lot of libraries to be installed
  • The requirements.txt file contains the library that the project depends on and the corresponding version


  • Use the following command to automatically install all dependencies
pip install -r requirements.txt

3. Virtual environment description

  • Creating a virtual environment is like re downloading a pure Python interpreter (which has onlypipandsetuptoolsTools)
  • Repeatedly creating virtual environment is similar to repeatedly downloading Python interpreter, which will consume a certain amount of hard disk space
  • At present, it is not recommended to use virtual environment. All modules are downloaded locally

4. Create a virtual environment

  • Open pychar —– > file —– > new project —– > pure python


  • Create successfully view the initial package: open pcharm —– > file —– > Settings —– > Project: [project name] —- > Python interpreter


  • Next time you create a new project, you can directly select the virtual environment that has been created