Day55 - django request life cycle flow chart, routing layer

django request life cycle flowchart

route matching

File name:

Professional Name: Routing Layer

urlpatterns = [
	path('URL extension',Function name)

If the suffix name of the URL entered by the browser matches the URL suffix name of the path, then the subsequent function call will be automatically triggered, and the following route matching will be ended at the same time.


Problem with trailing slash in routing suffix

We can see through practice that if we don't write slashes, we can also match


Because django will process the data twice, when the first match is made, the match fails; django will automatically let the browser add a slash for the second judgment

Of course we don't need django to do this, we can add and modify a configuration

APPEND_SLASH = False    # Default is not True

path converter

Application scenario: When the URL suffix is ​​not fixed, we can use a converter to match

Five converters:

  1. 'int': IntConverter(),
  2. 'path': PathConverter(),
  3. 'slug': SlugConverter(),
  4. 'str': StringConverter(),
  5. 'uuid': UUIDConverter(),

The more commonly used ones are int (integer) and str (string)

for example:

path('index/<int:id>/<str:info>', view.index)
here id and info is a variable, you can start it at will


  • The content matched by the converter will be passed in as a keyword parameter of the view function

  • There are several suffixes here, then several parameters must be passed in the view function

  • The name of the converter must correspond to the formal parameter of the view function

for example:

def index(request, year, info):

re_path regular matching

Grammatical structures:

re_path(regular expression, function name)

Once the regularity of the URL suffix can match the content, the following function will be automatically executed, and the matching of the entire route will be ended.


re_path('^index$', views.index)

When the suffix of the web page is not fixed, you can use a converter to match

Unnamed grouping for regular matching

Unnamed grouping can also be understood as literal meaning, group matching that cannot be aliased

Here we need to have knowledge about regularization: regular expression

for example:

re_path('^index/(\d+)/', views.test)

The content matched by the regular expression will be passed to the view function as the keyword parameter of the view function. At this time, the corresponding formal parameter is required to correspond

Regular matching of named groups

We can also understand it literally as aliasing the matching content instead

For aliasing in regular expressions, we use the method of ?P<alias>

for example:

re_path('^index/?P<id>\d+/?P<info>.*?/', views.index)

The content matched by the regular expression will be passed to the view function as the keyword parameter of the view function. At this time, the corresponding formal parameter is required to correspond

Note: In subsequent use, we obtain the matched data in the form of aliases

django version difference

  • In django1.11, only regular matching is supported, and the method is url()
  • In django2, 3, 4 versions, you can use path(), re_path()>>>url()

reverse parsing

  • definition

    As the function increases, more views will appear. Maybe the previously configured regular expression is not accurate enough, so the regular expression needs to be modified, but once the regular expression is modified, all the corresponding hyperlinks must be modified before. It is a troublesome thing, and some hyperlinks may be missed and forgotten to be modified. Is there a way to dynamically generate links based on regular expressions? It's the reverse analysis method.

    Reverse parsing: return a result that can access the corresponding route

  • Application scenarios

    • Hyperlinks in templates (eg: page jumps)
    • Redirect in view
  • Instructions

    1. Aliasing the correspondence in routing urls

      re_path('^index/?P<id>\d+/', views.index, name='index_view') 
      here name Corresponding data, we can get the previous suffix through this data, no matter how the suffix changes, it does not affect my ability to get
    2. When defining the url, you need to define the namespace attribute for include and the name attribute for the url
      When using, use the url tag in the template, use the reverse function in the view, and dynamically generate the address according to the regular expression to reduce the maintenance cost in the later period.

  • Use reverse parsing grammar

    • Use on HTML pages

      {%   url  'index_view'  %}
    • rear end

      from django.shortcuts import reverse

      When redirecting, use the method: return redirect(reverse('index_view'))

Emphasis: The three methods of reverse parsing are the same as path() re_path() url()

Anonymous and named reverse parsing

  • Nameless reverse parsing

    path('index/<str:info>/', views.index, name='index_view')


In the view function: reverse('index_view', args=('jason',)) must pass the corresponding number of values ​​according to the converter

In HTML file: {% url 'index_view' 'jason' %}

  • Famous reverse parsing

    re_path('^index/?P<id>\d+/?P<info>.*?/', views.index, name='index_view')


In the view function: reverse('index_view', kwargs={'id':id, 'info': info})

In HTML file: {% url 'index_view' 1 'jason' %}

route distribution

  • effect

    django The applications in can have their own independent templates folder static folder
     able to be based on django The multiple applications developed are completely independent, which is convenient for group development
  • general route

    path('app01/', include('app01.urls')),  # Go to the routing layer of app01
    path('app02/', include('app02.urls')),  # Go to the routing layer of app02
  • sub route

    path('after/', views.after)  # Find data under app01
    path('after/', views.after)  # Find the data under app02
  • scenes to be used

    When the project is very large and there are many applications, routing distribution can be used, which is very convenient!!!


Even if different apps use the same URL name, the URL namespace pattern allows you to uniquely reverse the named URL.

In a route distribution scenario, multiple applications cannot be resolved normally when reverse resolution alias conflicts are involved

  • Solution one

         path('app01/', include(('app01.urls', 'app01'), namespace='app01'))
         path('app01/', include(('app01.urls', 'app02'), namespace='app02'))
  • Solution two
    Aliases do not conflict

You can also ensure that there are no duplicate aliases under the django project.

for example:

way 1:namespace
	total route add namespace
	Apply reverse parsing auto-suggestion
    {% url 'app01:index_view' %}
    {% url 'app02:index_view' %}
way 2:Just make sure the reverse resolved aliases are not duplicated throughout the project!!!
	You can prefix the alias with the application name

Tags: Python Django

Posted by jroodman on Fri, 02 Sep 2022 08:21:46 +0930