【问题标题】:TemplateDoesNotExist at / error, even though index.html exists in the stated folderTemplateDoesNotExist at / 错误,即使 index.html 存在于所述文件夹中
【发布时间】:2019-08-26 11:00:14
【问题描述】:

跟进 [https://realpython.com/location-based-app-with-geodjango-tutorial/] 并实施附近的商店应用程序。但是,即使文件存在于指定的文件夹中,也会在 / 处获取 TemplateDoesNotExist。

尝试过的解决方案:

  1. 在“商店”应用中创建子目录(模板)

  2. 在 settings.py 中更改了 DIRS

settings.py

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:

django.template.loaders.filesystem.Loader: /home/username/sampleShops/nearbyshops/nearbyshops/shops (Source does not exist)
django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/admin/templates/nearbyshops/shops (Source does not exist)
django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/auth/templates/nearbyshops/shops (Source does not exist)
django.template.loaders.app_directories.Loader: /home/username/.local/lib/python3.6/site-packages/django/contrib/gis/templates/nearbyshops/shops (Source does not exist)

` 此外,我不在虚拟环境中工作(如果这会有所不同,尽管它不应该)

【问题讨论】:

  • 您的应用是否在 INSTALLED_APP 中包含模板?
  • 是的,它在 INSTALLED_APPS 中。

标签: django view python-3.6


【解决方案1】:

您可以尝试将“DIRS”替换为:

'DIRS': [os.path.join(BASE_DIR, 'templates')],

不要忘记将 /templates 文件夹放在设置文件的同一路径中。

【讨论】:

  • 设置文件在附近的商店,而我当前的模板文件夹在附近的商店/商店/模板中。您是建议我更改模板文件夹的位置还是更改 DIRS 中的路径?
  • 我用我的模板文件夹的位置与我的 settings.py 文件相同的位置尝试了上述方法。但是错误仍然存​​在。此外,错误表明 django 无法找到 shop/shop_list.html,而在任何地方都没有提到名为 shop_list.html 的文件(进行了 grep 搜索)。而不是 shop_list.html 它应该寻找 index.html。
  • 如果错误说找不到文件名是因为你的第一个问题已经解决了,你的目录找到了,请复制你的视图看看你是怎么调用模板的
【解决方案2】:

更改TEMPLATES

'DIRS': [os.path.join(BASE_DIR, 'templates')],

然后将模板保存在templates目录中。

your_app/
    models/
    temapltes/
        app_name/
            your_template.html

【讨论】:

  • /home/用户名/sampleShops/nearbyshops/shops/templates。这是我的模板的位置,但错误仍然存​​在。
  • 这是我当前的文件结构:sampleShop/nearthshops/nearthshops/settings.py urls.py template/index.html shop/admin.py models.py apps.py views.py tests.py manage .py ` 这就是我所说的:template_name = "nearbyshops/"。这是从商店/文件夹中的视图调用的。
  • 那么你如何从视图中返回模板名称
  • 好吧,它成功了,在 shop/ 中创建了一个模板文件夹,然后在其中添加了 index.html。
猜你喜欢
  • 2015-03-01
  • 2016-08-27
  • 1970-01-01
  • 2020-07-14
  • 2017-02-05
  • 2016-12-07
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多