【问题标题】:Django Cannot load a template in the template path of INSTALLED_APPSDjango 无法在 INSTALLED_APPS 的模板路径中加载模板
【发布时间】:2018-04-16 23:20:43
【问题描述】:

我正在使用 python 3.5.2 和 django 1.11.6。我的操作系统是win10。我无法在 installed_app 路径中加载我的模板。

我在“polls/template/polls/index.html”创建了一个文件。我还将应用程序 polls 添加到 INSTALLED_APPS 中,并将 TEMPLATES 中的 APP_DIRS 设置为 True。我无法弄清楚为什么 django 不会按照教程告诉我的那样将模板加载到 INSTALLED_APPS 模板文件夹中。

我使用以下代码sn-p在我的视图中加载模板。

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

我得到了这个 TemplateDoesNotExist。 我想知道为什么 django 不搜索路径“polls/template”。 django搜索到的路径如下。

  • django.template.loaders.app_directories.Loader: C:\Users\XXX\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\admin\templates\polls\index.html (来源不存在)
  • django.template.loaders.app_directories.Loader: C:\Users\XXX\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\templates\polls\index.html (来源不存在)

我的 INSTALLED_APPS 如下。

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

我的模板设置如下。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您的模板目录错误。它应该是 polls/templates/polls/index.html - templates 而不是 template。来自教程:

    首先,在您的投票目录中创建一个名为 templates 的目录。 Django 会在那里寻找模板。

    在您刚刚创建的模板目录中,创建另一个名为 polls 的目录,并在其中创建一个名为 index.html 的文件。换句话说,您的模板应该位于 polls/templates/polls/index.html

    【讨论】:

      【解决方案2】:

      另一种方法是,您可以在settings.py 中的DIRS 中的TEMPLATES 中设置模板路径。

      'DIRS': [str(ROOT_DIR.path('polls/templates/polls/')),],
      

      并设置ROOT_DIR是你项目的根目录,你可以使用environ设置根目录为:

      ROOT_DIR = environ.Path(__file__) - 2
      

      与直接添加 polls/templates/polls/index.html 相比,这很复杂,但这在一般情况下会有所帮助。当项目处于高阶段时,以一般方式进行转换非常重要。

      【讨论】:

        猜你喜欢
        • 2015-11-10
        • 2021-04-08
        • 2012-09-07
        • 2014-09-15
        • 2011-05-28
        • 2016-02-26
        • 2012-01-26
        • 1970-01-01
        • 2018-06-14
        相关资源
        最近更新 更多