SoFunction
Updated on 2025-05-14

Detailed explanation of the regular extraction parameter mechanism in routing matching in django

Django route matching example

Here is our sample code:

#Routefrom  import path, re_path

from . import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003),
    
    # Previous version 2.0 was url, but now it is re_path. It mainly matches through regular    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
]

# View layerdef month_archive(request,year,month):
    pass

Analysis of routing parameter delivery

How does django get and pass route parameters to view?

From the literal perspective, we can see that [regular path], so it cleverly utilizes the regular grouping characteristics and completes it through parameter unpacking characteristics. Let's demonstrate the general process below

Assumption: The path we visited is: articles/2021/11/

1. Use regular grouping matching to obtain grouping parameters

import re
path = "articles/2021/11/"
# Use regular to match routesres = (r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',path)

if not res:
    print("Match failed!")
else:
    # Extract path parameters and use grouping    kwargs = ()

By using grouping, we can get the path parameters in normal:

{'year': '2021', 'month': '11'}

2. We use the unpacking feature to pass the corresponding parameters to the view

# pseudocode, call view,# This situation may be more friendly, and it is called directly through keywords, which does not affect the parameter position when our method is defined.# But actually django uses positional parameter passingmonth_archive(request,**kwargs)

# The above is equivalent to month_archive(request, year="2021", month="11")

# Below is the positional parameter passing, note that this is further operation on the result of regular extraction# 1. Extract grouping resultsargs = ()  #('2021', '11')
# 2. Call the view, which limits its positionmonth_archive(request,*args)

# The above code is equivalent to  month_archive(request,"2011","11")

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.