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\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\d+)-(?P\d+)',views.detail)
urls.py
urlpatterns = [ url(r'detail-(?P\d+)-(?P \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\d+)/(?P \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