Python Django 命名空间模式的实现

yipeiwu_com5年前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设计】。

相关文章

Python3 中作为一等对象的函数解析

Python3 函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如pr...

通过实例解析Python调用json模块

这篇文章主要介绍了通过实例解析Python调用json模块,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍 今天介绍一种数据格式...

python 定时器每天就执行一次的实现代码

1.实现功能 编写python脚本一直运行,判断当下是否是新的一天,如果是就执行一次任务代码 2.具体实现代码 #-*-coding:utf-8 -*- __author__ = '...

windows环境中利用celery实现简单任务队列过程解析

windows环境中利用celery实现简单任务队列过程解析

这篇文章主要介绍了windows环境中利用celery实现简单任务队列过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一、背景...

python:按行读入,排序然后输出的方法

题目描述 给定n个字符串,请对n个字符串按照字典序排列。 输入描述: 输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。...