Python 不同Django应用程序中的相同文件名打开相同的模板
目前我创建了一个Django网站。我创建了一个应用程序Python 不同Django应用程序中的相同文件名打开相同的模板,python,django,django-urls,Python,Django,Django Urls,目前我创建了一个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'^heatingContr
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.url'),
在这两个视图中,我都添加了函数:
def index(request):
template = loader.get_template('index.html')
context = {}
return HttpResponse(template.render(context, request))
据我所知,Django将通过运行127.0.0.1:8000/app从app/template
文件夹打开index.html
,并通过运行127.0.0.1:8000从project/template
文件夹打开index.html
但它每次运行app/templates/index.html
文件时都会运行
我坚信在服务器应用程序中应该可以使用相同的目录名
我有什么问题吗?不,不是这样的。您需要为模板命名名称空间,即使它们位于应用程序中
--app
----templates
------app
--------index.html
或者,只保留单个项目级模板文件,但仍使用名称空间:
--project
----templates
------index.html
------app
--------index.html
无论哪种方式,现在都将模板引用为“app/index.html”
注意,您应该真正使用渲染
快捷方式:
def index(request):
context = {}
return render(request, 'app/index.html', context)
还要注意的是,项目级别的views.py并不常见。通常情况下,它会在应用程序中运行。不,它不是这样工作的。您需要为模板命名名称空间,即使它们位于应用程序中
--app
----templates
------app
--------index.html
或者,只保留单个项目级模板文件,但仍使用名称空间:
--project
----templates
------index.html
------app
--------index.html
无论哪种方式,现在都将模板引用为“app/index.html”
注意,您应该真正使用渲染
快捷方式:
def index(request):
context = {}
return render(request, 'app/index.html', context)
还要注意的是,项目级别的views.py并不常见。通常情况下,这将在应用程序中。您应该在templates文件夹中创建一个包含应用程序名称的文件夹。在此文件夹中,您可以放置html模板。在视图中,您将它们称为
appName/index.html
。查看此链接或您可以在该主题上找到的任何其他链接,您应该在templates文件夹中创建一个包含应用程序名称的文件夹。在此文件夹中,您可以放置html模板。在视图中,您将它们称为appName/index.html
。查看此链接或您可以在该主题上找到的任何其他链接
--app
----templates
------app
--------index.html