可能是一个简单的问题,因为我只是从Django开始。
我遵循着名的Django教程,将项目中的视图分离是相当明显的:
urlpatterns = patterns('',
url(r'^testpath/', include('test_app.urls')),
)
和test_app网址映射到“path /”
现在,在视图中我想避免路径的硬编码(示例来自教程):
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
其中polls/
是应用的硬编码路径。我相信必须有一种方法,因此可以在不改变代码的情况下在不同的应用程序中使用应用程序。
编辑:
项目模板目录:
/templates
index.html
/polls
index.html
我希望从/templates/polls/index.html
获取一个模板,而无需将polls
硬编码到视图中。所以在下一个项目中我可以举例:
/templates
index.html
/random_polls
index.html
(我知道app_directories.Loader
,但这意味着在应用中使用模板,这在我看来并不理想)
答案 0 :(得分:0)
Django将尝试找到模板的完整路径。因此,指定'polls/index.html'
或仅'index.html'
是相同的。您必须确保模板在具有指定路径的模板目录中适当可用。
您可以在设置中通过TEMPLATE_DIRS
指定模板目录。
查找模板目录也取决于TEMPLATE_LOADERS
设置。