相同的文件名在不同的 Django 应用程序中打开相同的模板
Same filename in differen Django apps opens the same template
目前我正在创建一个 Django 网站。我创建了一个应用程序。
project
--app
----templates
------index.html
----url.py
----views.py
--project
----templates
------index.html
----url.py
----views.py
在两个 url.py 中我都创建了 url 模式 url(r'^', views.index, name="index"),
并且项目中的 url.py 文件包含 url(r'^heatingControll/', include('heatingControll.urls')),
.
在两个视图中我都添加了函数:
def index(request):
template = loader.get_template('index.html')
context = {}
return HttpResponse(template.render(context, request))
据我了解,Django 将通过 运行 127.0.0.1:8000/app 和 运行 127.0.0.1 从 app/template
文件夹中打开 index.html
:8000 来自 project/template
文件夹的 index.html
。
但是每次 app/templates/index.html
文件都 运行s。
我坚信应该可以在多个应用程序中使用相同的目录名称。
我的问题是什么?
不,事情不是这样的。您需要为模板命名空间,即使它们在应用程序中也是如此。
--app
----templates
------app
--------index.html
或者,只保留单个项目级模板文件,但仍使用命名空间:
--project
----templates
------index.html
------app
--------index.html
无论哪种方式,您现在都将模板引用为 "app/index.html"
。
注意,你真的应该使用 render
快捷方式:
def index(request):
context = {}
return render(request, 'app/index.html', context)
另请注意,拥有项目级 views.py 并不常见。通常这会在应用程序中。
目前我正在创建一个 Django 网站。我创建了一个应用程序。
project
--app
----templates
------index.html
----url.py
----views.py
--project
----templates
------index.html
----url.py
----views.py
在两个 url.py 中我都创建了 url 模式 url(r'^', views.index, name="index"),
并且项目中的 url.py 文件包含 url(r'^heatingControll/', include('heatingControll.urls')),
.
在两个视图中我都添加了函数:
def index(request):
template = loader.get_template('index.html')
context = {}
return HttpResponse(template.render(context, request))
据我了解,Django 将通过 运行 127.0.0.1:8000/app 和 运行 127.0.0.1 从 app/template
文件夹中打开 index.html
:8000 来自 project/template
文件夹的 index.html
。
但是每次 app/templates/index.html
文件都 运行s。
我坚信应该可以在多个应用程序中使用相同的目录名称。
我的问题是什么?
不,事情不是这样的。您需要为模板命名空间,即使它们在应用程序中也是如此。
--app
----templates
------app
--------index.html
或者,只保留单个项目级模板文件,但仍使用命名空间:
--project
----templates
------index.html
------app
--------index.html
无论哪种方式,您现在都将模板引用为 "app/index.html"
。
注意,你真的应该使用 render
快捷方式:
def index(request):
context = {}
return render(request, 'app/index.html', context)
另请注意,拥有项目级 views.py 并不常见。通常这会在应用程序中。