Django之URL的命名空间和命名模式

Django之URL的命名空间和命名模式

http://blog.csdn.net/xiaobing_blog/article/details/11003643


 

django URL模式浅析


http://blog.csdn.net/laughing2333/article/details/51674905




Namespacing URL names

The tutorial project has just one app, polls. In real Django projects, there might be five, ten, twenty apps or more. How does Django differentiate the URL names between them? For example, the polls app has a detail view, and so might an app on the same project that is for a blog. How does one make it so that Django knows which app view to create for a url when using the {% url %} template tag?

The answer is to add namespaces to your URLconf. In the polls/urls.py file, go ahead and add an app_name to set the application namespace:

polls/urls.py
from django.conf.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

Now change your polls/index.html template from:

polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

to point at the namespaced detail view:

polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

xys友情提醒:

URL命名空间是用于模板文件中对URL(所谓URL是浏览器访问时的网络地址)的反向引用,一般会使用模板标签{% url %}

例如在index.html中

{% url 'polls:detail' question.id %}"

这根模板文件的命名空间(其实质是本地的相对路径)不一样:模板文件的命名空间的应用场景是,在每个APP下建立appname/templates/appname/,然后在该目录下再放模板文件(index.html)。然后在需要引用模板文件的地方,采用模板文件相对地址硬编码时,形式如下:appname/index.html.

例如在views.py中

def index(request):     #return HttpResponse("Hello, world. You're at the polls index.")     return render(request,'polls/index.html')

或者index.html中

<li><a href="/polls/xxx.html">{{ question.question_text }}</a></li>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值