您的位置:首页 > 编程语言 > Go语言

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

2017-09-12 11:24 441 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django url