Django NEWBIE - TemplateDoesNotExist

(Каталог моего проекта называется test, а приложение, о котором идет речь, называется posts)

Django пытался загрузить эти шаблоны, в таком порядке:

Использование движка django:

django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/test/posts/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/auth/templates/index.html (Source does not exist)

Views.py

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


def index(request):
     return render(request,'templates/index.html')

Urls.py

from django.urls import path
from . import views

urlpatterns=[
    path('', views.index)
]

Я упомянул приложение в Settings.py, так что это, вероятно, не должно быть проблемой.

Что я делаю не так?

filetree

Шаблон размещается в каталоге posts/templates/posts/. Если вы включите APP_DIRS, то он будет искать все каталоги templates/ во всех приложениях, но он все равно будет размещен в каталоге posts/, следовательно, вы получите доступ к шаблону с помощью:

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

def index(request):
     return render(request,'posts/index.html')

Вам необходимо указать каталоги шаблонов в settings.py.

settings.py

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"], # BASE_DIR / Your-templates-folder
        "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",
            ],
        },
    },
]

Поскольку у вас index.html находится в папке posts, путь к шаблону в views.py должен быть templates/posts/index.html

views.py

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


def index(request):
     return render(request, 'templates/posts/index.html')
Вернуться на верх