Django中的反向解析

前提:

url(r'^app/', include('app.urls',namespace='app')),

url('^relation',views.relation,name='relation'),

模板函数中的反向解析:

<a href="{% url 'app:relation' %}">相对路径3</a>

无论url怎么改变,只要视图函数的名称不变,模板都可以反向解析到该视图函数。

若url中是非关键字参数:

url('^bbb/(d+)/(d+)/(d+)',views.bbb,name='bbb'),

反向解析按照顺序传参数:

<a href="{% url 'app:bbb' 2099 99 99 %}">相对路径4</a>

若url中是关键字参数:

url('^ccc/(?P<year>d+)/(?P<month>d+)/(?P<day>d+)',views.ccc,name='ccc'),

反向解析可以不按照顺序传参数,但传参时要写关键字:

<a href="{% url 'app:ccc' month=10 day=13 year=2000%}">相对路径5</a>

视图函数重定向的反向解析:

url('^fromHere',views.fromHere),
url('^toHere',views.toHere,name='toHere'),

视图函数中的写法:

def fromHere(request):
return redirect(reverse('app:toHere'))
def toHere(request):
return HttpResponse('到这啦')

这样无论url中的toHere怎么改变,只要视图函数名叫toHere就可以重定向到它。

若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)+"")
Fake it,till you make it
原文地址:https://www.cnblogs.com/wusir66/p/9838960.html