Django-URL路由系統
阿新 • • 發佈:2018-07-16
message imp over def 基本用法 clas 獲取 module gem
django的路由系統:
一、基本用法:
1.path(‘index‘, views.index), # 通過類的方式創建url映射 2.path(‘home‘, views.Home.as_view()), # 通過正則表達式的方式 註意這種方式不能通過path的方式關聯,否則正則表達式無效,通過 from django.conf.urls import url,然後通過url(regx,views,kwargs,name)進行url的正則表達式的匹配 3.url(r‘detail-(\d+)‘,views.detail), 4.url(r‘detail-(\d+)-(\d+)‘,views.detail),5.url(r‘detail-(?P<nid>\d+)‘,views.detail)
實戰:
1.通過url(r‘detail-(\d+)-(\d+)‘,views.detail)
urls.py
urlpatterns = [ url(r‘detail-(\d+)-(\d+)‘,views.detail), ]
views.py
# 方式一: def detail(request,nid,uid): pass # 方式二: def detail(request,*args,**kwargs): pass
以上方式,nid和uid關聯的參數,適合調用參數有關系,比如調用‘http://127.0.0.1:8080/detail-1-2‘,則 nid = 1, uid = 2;方式二的args = (1,2),kwargs = {}
可是這不是我們想要的,我們如何讓nid和uid和傳遞的參數關聯上,還是通過正則表達式解決參數關聯問題
2.通過url(r‘detail-(?P<nid>\d+)-(?P<uid>\d+)‘,views.detail)
urls.py
urlpatterns = [ url(r‘detail-(?P<nid>\d+)-(?P<uid>\d+)‘,views.detail) ]
views.py
# 方式一: def detail(request,nid,uid): pass
def detail(request,uid,nid):
pass # 方式二: def detail(request,*args,**kwargs): pass
這樣無論我們如何更換參數的位置,我們的獲取的nid都是‘/detail-1-2‘的第一個參數值,uid始終為第二個參數值;而才是方式二的參數變為 args=() kwargs={‘nid‘: 1,‘uid‘:2}
二、進階
1.name(對URL路由關系進行命名,以後可以根據名稱生成你想要的URL)
urls.py
urlpatterns = [ url(‘homemodule‘,views.home,name=‘m1‘), url(r‘disovermodule/(\d+)/(\d+)‘,views.discover,name=‘m2‘), url(r‘messagemodule/(?P<nid>\d+)/(?P<uid>\d+)‘,views.message,name=‘m3‘) ]
views.py
def func(request,*args,**kwargs): from django.url import reverse url1 = reverse(‘m1‘) #/homemodule/ url2 = reverse(‘m2‘,args=(1,2)) #/discovermodule/1/2 url3 = reverse(‘m3‘,kwargs={‘nid‘:3,‘uid‘:4}) # /messagemodule/3/4
xxx.html
{% url ‘m1‘ %} #/homemodule
{% url ‘m2‘ 1 2 %} #/discovermodule/1/2
{% url ‘m3‘ nid=3 uid=4 %} #/messagemodule/3/4
註意獲取當前URL
request.path_info
Django-URL路由系統