前提:app
url(r'^app/', include('app.urls',namespace='app')), url('^relation',views.relation,name='relation'),
模板函數中的反向解析:函數
<a href="{% url 'app:relation' %}">相對路徑3</a>
不管url怎麼改變,只要視圖函數的名稱不變,模板均可以反向解析到該視圖函數。url
若url中是非關鍵字參數:spa
url('^bbb/(\d+)/(\d+)/(\d+)',views.bbb,name='bbb'),
反向解析按照順序傳參數:code
<a href="{% url 'app:bbb' 2099 99 99 %}">相對路徑4</a>
若url中是關鍵字參數:blog
url('^ccc/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)',views.ccc,name='ccc'),
反向解析能夠不按照順序傳參數,但傳參時要寫關鍵字:io
<a href="{% url 'app:ccc' month=10 day=13 year=2000%}">相對路徑5</a>
視圖函數重定向的反向解析:模板
url('^fromHere',views.fromHere), url('^toHere',views.toHere,name='toHere'),
視圖函數中的寫法:class
def fromHere(request): return redirect(reverse('app:toHere')) def toHere(request): return HttpResponse('到這啦')
這樣不管url中的toHere怎麼改變,只要視圖函數名叫toHere就能夠重定向到它。request
若url中是非關鍵字參數:
url('^fromHere',views.fromHere), url('^toHere/(\d+)/(\d+)/(\d+)',views.toHere,name='toHere'),
視圖函數中的寫法:
def fromHere(request): return redirect(reverse('app:toHere',args=(2018,8,8))) def toHere(request,year,month,day): return HttpResponse(str(year) + "年"+str(month) +"月"+str(day)+"日")
若url中是關鍵字參數:
url('^fromHere',views.fromHere), url('^toHere/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)',views.toHere,name='toHere'),
視圖函數中的寫法:
def fromHere(request): return redirect(reverse('app:toHere',kwargs={"year":2020,"month":10,"day":10})) def toHere(request,year,month,day): return HttpResponse(str(year) + "年"+str(month) +"月"+str(day)+"日")