Python Django 命名空间模式的实现

yipeiwu_com6年前Python基础

新建一个项目 app02

在 app02/ 下创建 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 目录下创建 /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 页面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python银行系统实战源码

本文实例为大家分享了Python银行系统的具体代码,供大家参考,具体内容如下 import time import random import pickle import os...

利用Opencv中Houghline方法实现直线检测

利用Opencv中Houghline方法实现直线检测

利用Opencv中的Houghline方法进行直线检测—python语言 这是给Python部落翻译的文章,请在这里看原文。 在图像处理中,霍夫变换用来检测任意能够用数学公式表达的形状,...

Python装饰器实现几类验证功能做法实例

最近新需求来了,要给系统增加几个资源权限。尽量减少代码的改动和程序的复杂程度。所以还是使用装饰器比较科学 之前用了一些登录验证的现成装饰器模块。然后仿写一些用户管理部分的权限装饰器。 比...

编程语言Python的发展史

编程语言Python的发展史

Python是我喜欢的语言,简洁、优美、易用。前两天,我很激昂地向朋友宣传Python的好处。 “好吧,我承认Python不错,但它为什么叫Python呢?” “呃,似乎是一个电视剧的名...

15行Python代码实现网易云热门歌单实例教程

15行Python代码实现网易云热门歌单实例教程

0. 引言 马上314情人节就要来了,是否需要一首歌来抚慰你,受伤或躁动的心灵。来吧,今天教你用15行代码搞定热门歌单。学起来并听起来吧。 本文使用的是Selenium模块,它是一个自...