Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django Routing

Django Routing

Simply put, routing determines the corresponding handler based on the URL requested by the user and returns the processing result; that is, it establishes a mapping relationship between URLs and Django's views.

Django routing is configured in urls.py; each configuration in urls.py corresponds to a corresponding processing method.

Django's urls.py configuration differs slightly across versions:

Django 1.1.x version

url() method: Both normal paths and regex paths can be used; you need to manually add the regex start/end restriction symbols yourself.

Example

from

django.

conf

.

urls

import

url

Using url requires importing

urlpatterns

=

[

    url

(

r

'^admin/$'

,

admin.

site

.

urls

)

,

    url

(

r

'^index/$'

,

views.

index

)

,

Normal path

    url

(

r

'^articles/([0-9]{4})/$'

,

views.

articles

)

,

Regex path

]

Django 2.2.x and later versions

Example

from

django.

urls

import

re_path

Using re_path requires importing

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

    path

(

'index/'

,

views.

index

)

,

Normal path

    re_path

(

r

'^articles/([0-9]{4})/$'

,

views.

articles

)

,

Regex path

]

**Summary:** The url in Django 1.1.x and the re_path in Django 2.2.x are used in the same way.


Grouping in regex paths

Unnamed groups in regex paths

Unnamed groups pass arguments by position, one-to-one correspondence.

In views, apart from request, the number of other formal parameters must match the number of groups in urls.

urls.py

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

    re_path

(

"^index/([0-9]{4})/$"

,

views.

index

)

,

]

views.py

from

django.

shortcuts

import

HttpResponse

def

index

(

request

,

year

)

:

   

print

(

year

)

One formal parameter represents the content of one group in the path, matched in order

   

return

HttpResponse

(

'Runoob Tutorial'

)

Named groups in regex paths

Syntax:

(?P<组名>正则表达式)

Named groups pass arguments by keyword, independent of positional order.

In views, apart from request, the number of other formal parameters must match the number of groups in urls, and the formal parameter names in views must correspond to the group names in urls.

urls.py

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

    re_path

(

"^index/(?P[0-9]{4})/(?P[0-9]{2})/$"

,

views.

index

)

,

]

views.py

from

django.

shortcuts

import

HttpResponse

def

index

(

request

,

year

,

month

)

:

   

print

(

year

,

month

)

One formal parameter represents the content of one group in the path, matched by keyword

   

return

HttpResponse

(

'Runoob Tutorial'

)

Named groups in regex paths

Route distribution (include)

Existing problems: In a Django project, multiple app directories sharing one urls can easily cause confusion and is inconvenient for later maintenance.

Solution: Use route distribution (include) so that each app directory has its own urls.

Steps:

Example

from

django.

contrib

import

admin

from

django.

urls

import

path

,

include

Import include from django.urls

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

    path

(

"app01/"

,

include

(

"app01.urls"

)

)

,

    path

(

"app02/"

,

include

(

"app02.urls"

)

)

,

]

In each app directory, write your own urls.py file to perform path jumping.

app01 directory:

from django.urls import path,re_path 

from app01 import views # 从自己的 app 目录引入 views 

urlpatterns = [ 

    re_path(r'^login/(?P[0-9]{2})/$', views.index, ),

] 

app02 directory:

from django.urls import path,re_path

from app02 import views # 从自己的 app 目录引入views 

urlpatterns = [ 

    re_path("^xxx/(?P[0-9]{4})/$", views.xxx), 

]

Write respective view functions in the views.py file under each app directory.


Reverse resolution

As functionality increases and the url at the routing layer changes, you need to change the urls in the corresponding view layer and template layer, which is very troublesome and inconvenient to maintain.

At this point we can use reverse resolution: when the routing layer url changes, the changed url is dynamically reverse-resolved in the view layer and template layer, eliminating the need for manual modification.

Reverse resolution is generally used for hyperlinks in templates and redirects in views.

Normal path

Give an alias to a route in urls.py,name="route alias"。

path("login1/", views.login, name="login")

In views.py, import reverse from django.urls and use reverse("route alias") reverse resolution:

return redirect(reverse("login"))

In the HTML files in the templates directory, use {% url "route alias" %} for reverse resolution.

Regex path (unnamed group)

Give an alias to a route in urls.py,name="route alias"。

re_path(r"^login/([0-9]{2})/$", views.login, name="login")

In views.py, import reverse from django.urls and use reverse("route alias", args=(parameter matching the regex,)) for reverse resolution.

return redirect(reverse("login",args=(10,)))

In the HTML files in the templates directory, use {% url "route alias" parameter matching the regex %} for reverse resolution.

 

Regex path (named group)

Give an alias to a route in urls.py,name="route alias"。

re_path(r"^login/(?P[0-9]{4})/$", views.login, name="login")

In views.py, import reverse from django.urls and use **reverse("route alias", kwargs={"group_name": parameter matching the regex}) ** for reverse resolution.

return redirect(reverse("login",kwargs={"year":3333}))

In the HTML files in the templates directory, use {% url "route alias" group_name=parameter matching the regex %} for reverse resolution.




Namespacing

A namespace (English: Namespace) represents the visibility scope of identifiers.

An identifier can be defined in multiple namespaces, and its meaning in different namespaces is unrelated.

Any identifier can be defined in a new namespace; they will not conflict with any duplicate identifiers, because duplicate definitions are all in other namespaces.

**Problem:** The route alias name has no scope. When reverse-resolving a URL, Django searches sequentially across the whole project and returns immediately when it finds the first URL specified by a route alias name. When the same route alias name is defined in urls under different app directories, it may cause URL reverse resolution errors.

**Solution:** Use namespaces.

Normal path

The format for defining a namespace (include contains a tuple) is as follows:

include(("app名称:urls","app名称"))

Example:

path("app01/", include(("app01.urls","app01"))) 

path("app02/", include(("app02.urls","app02")))

Use the same route alias in app01/urls.py.

path("login/", views.login, name="login")

To use the namespace in views.py, the syntax format is as follows:

reverse("app名称:路由别名")

Example:

return redirect(reverse("app01:login")

To use the namespace in the HTML files of the templates directory, the syntax format is as follows:

{% url "app名称:路由别名" %}

Example: