【问题标题】:Django urls can't find templates with HTML fileDjango url 找不到带有 HTML 文件的模板
【发布时间】:2019-12-24 00:59:36
【问题描述】:

我正在尝试在我的 Django ToDo 应用程序中创建视图。但是有一个 TemplateDoesNotExist 错误。我正在寻找解决方案,但它仍然无法正常工作。

这是我在主文件夹中的 urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('todoapp_api.urls')),
]

那么我的应用文件夹是“todoapp_api” 我有 urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.app, name='app'),
]

我的views.py看起来像这样

from django.shortcuts import render
from django.http import HttpResponse


def app(request):
    return render(request, 'todoapp_api/app.html')

【问题讨论】:

  • 'todoapp_api/app.html' 在哪里?
  • 您是否将模板文件夹添加到 settings.py 文件中?
  • 像这样:'DIRS': ['todoapp_api/templates']

标签: python django django-views django-urls


【解决方案1】:

您有两个选择: 目录结构一: todoapp_ap/templates/todoapp_api/app.html

或者按照目录结构2: 1. 在您的根目录中创建一个全局模板文件夹。 2. 在其中创建 todoapp_api 文件夹并放置您想要的任何模板文件。

在你的 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',
            ],
        },
    },
]

通过这个:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        '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',
            ],
        },
    },
]

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2011-10-05
    • 2019-07-03
    • 2018-01-02
    相关资源
    最近更新 更多