Django的URL反向解析

Django的URL反向解析功能在模板文件中和Python程序中有不同的调用方法:

  • 在模板文件中用{%url%}标签反向解析
  • 在Python程序中有django.urls.reverse()函数调用反向解析

url映射规则:

from django.urls import path,include
from app import views
urlparterns = [
    path('login/', views.login,name='login')       
]

 

其中定义了一个URL映射,并通过name参数将该映射命名为login。在需要获得该URL的模板文件中可以通过{%URL%}标签进行声名,比如:

<a href="{% URL 'login' %}">
    Login
</a>

其中用映射名“login”作为反向解析的参数,该模板解析后的结果为:

<a href="/login/">
Login
</a>

而在Python代码与模板文件中的反向解析调用方式是使用reverse函数,比如:

from django.shortcuts import redirect
from django.urls import reverse

def login(request):
    return redirect(reverse(index))

 

带参数的反向解析:反向解析还支持在URL路径和被调用函数中有参数的情况,比如对于带参数的映射:

from django.urls import path,inlude
from app import views

urlpatterns = [
    path('index/?P<user_id>',views.index,name='re_index'),
]

然后在模板文件反向解析中,可以直接在{%URL%}标签中添加参数,如:

<a href="{% URL 're_index',1 %}">
    用户user_id为1
</a>

<!--解析后结果为-->
<a href="/index/1/">
    用户user_id为1
</a>

在Python程序中反向解析如下:

from django.urls import reverse
from django.shortcuts import redirect

def redirect_to_index_1(request):
    return redirect(reverse(index,args=(1,)))

 

posted @ 2021-12-02 15:55  LiQ0112  阅读(182)  评论(0)    收藏  举报