django 引用{% url "name"%} 避免链接硬编码<转>

http://blog.chinaunix.net/uid-11390629-id-4059271.html

前提条件,为每个url指定name且name值要唯一。比如:
项目中的url.py文件:
urlpatterns = patterns('',
    url(r'^$',TemplateView.as_view(template_name='welcome.html'),name="home"),
    url(r'^accounts/', include('accounts.urls', namespace="accounts")),
    url(r'^admin/', include(admin.site.urls)),
)

accounts应用中的url.py文件:
urlpatterns = patterns('',
    url(r'^login/$',  login, name="login"),
    url(r'^logout/$', logout, name="logout"),
    url(r'^register/$', views.register,name="register"),
)

1.template模板中引用:
首页url: "/"
可表示为:{%url "home" %}

应用中的链接url: "/accounts/login"
可表示为:{%url "accounts:login" %} 

next默认赋值:
<input type="hidden" name="next" value="{{ next|escape }}}" />

当跳转到"/home"时,{{ next|add:'/home/' }}这样写就太傻
可写为:<input type="hidden" name="next" value="{%url "home"%}" />

2.views中的引用:
from django.core.urlresolvers import reverse

定向到“/”
HttpResponseRedirect(reverse("home"))

定向到“/accounts/login”
HttpResponseRedirect(reverse("accounts:login"))

你可能感兴趣的:(django)