0

可能是一个简单的问题,因为我刚开始使用 Django。

我遵循了著名的 Django 教程,并且从项目中解耦视图是相当明显的:

urlpatterns = patterns('',
    url(r'^testpath/', include('test_app.urls')),
)

并且 test_app url 映射到“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,但这意味着在应用程序中使用模板,这在我看来并不理想)

4

1 回答 1

0

Django 将尝试找到模板的完整路径。所以指定'polls/index.html'或只是'index.html'相同。您必须确保模板在具有指定路径的模板目录中适当可用。

您可以通过设置指定模板目录TEMPLATE_DIRS

查找模板目录也取决于TEMPLATE_LOADERS设置。

加载模板中的更多详细信息

于 2013-05-01T11:48:29.733 回答