Django: Шаблон шаблонов не найден при попытке доступа к шаблону рендеринга функций
У меня есть структура файла:
Resilience_Radar_R2/Leadership_Questions_App/Leadership_Questions/templates/questions.html
Я определил функцию riskindex, которая должна вывести файл questions.html и включить на страницу некоторый текст.
У меня также есть индексная функция, которая просто отправляет HttpResponse, если запрос пустой
Функция индекса работает нормально по адресу http://127.0.0.1:8000/Leadership_Questions_App/
но рискиндекс по адресу http://127.0.0.1:8000/Leadership_Questions_App/riskindex возвращает ошибку:
TemplateDoesNotExist at /Leadership_Questions_App/riskindex/
Leadership_Questions/questions.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/Leadership_Questions_App/riskindex/
Django Version: 5.0.7
Exception Type: TemplateDoesNotExist
Exception Value:    
Leadership_Questions/questions.html
Exception Location: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py, line 19, in get_template
Raised during:  Leadership_Questions_App.views.riskindex
Python Executable:  /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/bin/python
Python Version: 3.12.3
Python Path:    
['/Users/xxx/Documents/Work/Python '
 'Projects/Dashboard/Reslience_Radar_R2',
 '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip',
 '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12',
 '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload',
 '/Users/xxx/Documents/Work/Python '
 'Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages']
Server time:    Sat, 10 Aug 2024 19:44:06 +0000
Каталог терминала: (.venv) (base) xxx@MacBook-Pro Reslience_Radar_R2 %
Похоже, что он ищет в другом каталоге, а не в том, где находится код python.
Reslience_Radar_R2 urls.py
rom django.contrib import admin
from django.urls import include, path
urlpatterns = [
    path('admin/', admin.site.urls),
    path('Leadership_Questions_App/', include("Leadership_Questions_App.urls"))
]
Leadership_Questions_App
urls.py
from django.urls import path
from . import views
urlpatterns = [
    
    path("", views.index, name="index"),
    path("riskindex/", views.riskindex, name="riskindex"),
    
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
    return HttpResponse("Leadership Questions")
def riskindex(request):
    description = "This is text"
    return render (request, "Leadership_Questions/questions.html", {
        "text": description
        }
        )
Leradership_Questions_App/templates questions.html
<!DOCTYPE html>
<html>
    <head>
        <title>Leadership Questions</title>
    </head>
    <body>
        {{ description }}
    </body>
</html>
templates in 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',
            ],
        },
    },
]
Я попробовал изменить путь к функции riskindex и получил ту же ошибку:
def riskindex(request):
    description = "This is text"
    return render (request, "questions.html", {
        "text": description
        }
        )
Я пробовал удалить функцию index и path: и заставить функцию riskindex быть для пустого пути, но я получаю ту же ошибку "Template not found":
Internal Server Error: /Leadership_Questions_App/
Traceback (most recent call last):
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R2/Leadership_Questions_App/views.py", line 10, in riskindex
    return render (request, "Leadership_Questions/questions.html", {
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/shortcuts.py", line 25, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py", line 61, in render_to_string
    template = get_template(template_name, using=using)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/beyondscorecard/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py", line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: Leadership_Questions/questions.html
[10/Aug/2024 19:55:14] "GET /Leadership_Questions_App/ HTTP/1.1" 500 78688
                
У меня есть файловая структура:
Resilience_Radar_R2/Leadership_Questions_App/Leadership_Questions/templates/questions.html
В самом приложении есть каталог с именем template. Таким образом, должно быть:
Resilience_Radar_R2/Leadership_Questions_App/templates/Leadership_Questions/questions.html
Примечание: Модули Python обычно пишутся в snake_case, а не PascalCase, так что это должно быть
leadership_questions, а не.Leadership_Questions_App
Кажется, вы забыли добавить новое приложение в список установленных_приложений.
Ваши установленные_приложения должны выглядеть следующим образом:
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "Leadership_Questions_App",
]