Django中的反向解析

前提: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)+"")
相关文章
相关标签/搜索