Python Django 命名空間模式的實現(xiàn)
新建一個項目 app02

在 app02/ 下創(chuàng)建 urls.py:
from django.conf.urls import url from app02 import views urlpatterns = [ url(r'^blog/', views.test, name="blog"), ]
app01/urls.py:
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^blog/', views.blog, name="blog"), ]
這兩個都有 blog/ 路徑,且都名為 blog,訪問的話就不知道該訪問哪一個
這時候需要用到命名空間
在 templates 目錄下創(chuàng)建 /books/blog.html 和 /news/blog.html

app01/views.py:
from django.shortcuts import render def test(request): return render(request, "test.html") def blog(request): return render(request, "news/blog.html") # news 前不要加 /
app02/views.py:
from django.shortcuts import render def test(request): return render(request, "books/blog.html") # books 前不要加 /
mysite2/urls.py:
from django.conf.urls import url, include from app01 import views from app01 import urls as app01_urls from app02 import urls as app02_urls urlpatterns = [ url(r'^test/', views.test), url(r'^blog/', include(app01_urls, namespace="news")), url(r'^blog/', include(app02_urls, namespace="books")), ]
test.html:
<a href="{% url 'books:blog' %}" rel="external nofollow" >書籍</a>
<a href="{% url 'news:blog' %}" rel="external nofollow" >新聞</a>
這里用的是 namespace_name 格式來獲取 url 路徑
訪問:http://127.0.0.1:8000/test/

點擊“新聞”

跳到了:http://127.0.0.1:8000/blog/blog/,返回的是 /news/blog.html 頁面
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
linux環(huán)境下的python安裝過程圖解(含setuptools)
這篇文章主要介紹了linux環(huán)境下的python安裝過程圖解(含setuptools),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
python如何實現(xiàn)excel數(shù)據(jù)添加到mongodb
本文介紹了python是如何實現(xiàn)excel數(shù)據(jù)添加到mongodb,為了將數(shù)據(jù)導入mongodb,引入了pymongo,xlrd包,需要的朋友可以參考下2015-07-07
Python中raise用法簡單實例(超級詳細,看了無師自通)
python中raise語句用于手動觸發(fā)異常,通過raise語句可以在代碼中顯式地引發(fā)異常,從而使程序進入異常處理流程,下面這篇文章主要給大家介紹了關于Python中raise用法的相關資料,需要的朋友可以參考下2024-03-03

