Django 模板 - 如何获得正确的根与应用程序查找

问题描述 投票:0回答:1

如何让视图从相应的应用程序(根应用程序与子应用程序)加载模板?

这是完整的结构:

  1. 创建 django 项目 -
    universe
  2. 创建了一个应用程序 - 我们称之为
    earth
  3. /
    ->
    universe/universe/templates/main.html
  4. 创建了(容器)模板
  5. /earth
    ->
    universe/earth/templates/main.html
  6. 创建了(容器)模板
  7. 分别在
    /
    /earth
    universe/universe/templates/index.html
    universe/earth/templates/index.html
    创建了(内容)模板。
  8. universe/universe/views.py
    中,我有:
    from django.shortcuts import render
    
    def index(request):
      context = {}
      return render(request, 'index.html', context)
    
  9. universe/earth/views.py
    中,我也有同样的:
    from django.shortcuts import render
    
    def index(request):
      context = {}
      return render(request, 'index.html', context)
    

当我运行此程序时,出现错误

TemplateDoesNotExist at /
。为什么找不到模板?

如果我更新

universe/universe/settings.py

TEMPLATES = [
  ...
  'DIRS': [
    BASE_DIR / 'universe/templates'
  ]
]

仅选取

universe
模板。

如何确保当我根据应用程序引用正确的

index.html
时?

django django-templates
1个回答
0
投票

如果您有应用程序明智的模板目录,那么您需要在

DIRS
中指定所有目录。所以,它被捡起来了。

TEMPLATES = [
  ...
  'DIRS': [
    BASE_DIR / 'universe/templates',
    BASE_DIR / 'earth/templates',
    ...
    # if you have templates director at root level then also need to add this
    # BASE_DIR / 'templates',
  ]
]

此外,如果您在多个目录中有相同名称的模板,那么在视图中您必须提及要为其渲染模板的文件夹名称。

您的情况:

# In universe/universe/views.py
from django.shortcuts import render

def index(request):
  context = {}
  return render(request, 'universe/index.html', context)

# In universe/earth/views.py
from django.shortcuts import render

def index(request):
  context = {}
  return render(request, 'earth/index.html', context)
© www.soinside.com 2019 - 2024. All rights reserved.