Python Django 命名空间模式的实现
作者:Sch01aR# 时间:2023-10-06 05:34:28
新建一个项目 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 页面
来源:https://www.cnblogs.com/sch01ar/p/11285735.html
标签:python,django,命名,空间,模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 批量修改 labelImg 生成的xml文件的方法
2022-09-03 12:04:23
Mysql存储过程学习笔记--建立简单的存储过程
2024-01-23 14:41:21
![](https://img.aspxhome.com/file/2023/0/71120_0s.png)
注册表单的细节问题
2008-05-24 08:43:00
![](https://img.aspxhome.com/file/UploadPic/20085/24/200852485213503s.jpg)
python读取Excel实例详解
2021-05-25 16:10:44
Python3.4解释器用法简单示例
2022-01-04 10:30:39
package.json版本号符号^和~前缀的区别
2024-05-02 17:36:11
![](https://img.aspxhome.com/file/2023/2/129492_0s.png)
bak文件怎么打开 2000w数据怎么打开?
2024-01-12 19:30:43
![](https://img.aspxhome.com/file/2023/0/96200_0s.jpg)
Fabric 应用案例
2021-10-11 13:13:01
使用Python实现牛顿法求极值
2021-10-14 15:10:21
![](https://img.aspxhome.com/file/2023/7/131357_0s.jpg)
asp如何获知文件最后的修改日期和时间?
2009-11-24 20:49:00
python unichr函数知识点总结
2022-02-03 11:48:31
Python 创建子进程模块subprocess详解
2022-02-21 06:47:39
Python解决两个整数相除只得到整数部分的实例
2021-12-29 23:29:21
基于Python中求和函数sum的用法详解
2022-12-05 23:26:18
Python实现视频裁剪的示例代码
2022-07-20 07:14:14
![](https://img.aspxhome.com/file/2023/3/85373_0s.png)
在SQL Server中实现最短路径搜索的解决方法
2024-01-24 13:47:10
![](https://img.aspxhome.com/file/2023/0/127990_0s.png)
python/Matplotlib绘制复变函数图像教程
2023-08-03 07:36:43
![](https://img.aspxhome.com/file/2023/7/61207_0s.jpg)
Mysql中一千万条数据怎么快速查询
2024-01-15 06:57:05
MySQL存储过程savepoint rollback to
2008-12-03 16:02:00
Oracle数据库逻辑备份的SH文件
2010-07-27 13:26:00