Home > Enterprise >  Django NEWBIE - TemplateDoesNotExist
Django NEWBIE - TemplateDoesNotExist

Time:12-30

(My project directory is called test and the app in question is called posts)

Django tried loading these templates, in this order:

Using engine 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)
]

I have mentioned the app in Settings.py so that probably shouldn't be an issue.

What am I doing wrong ?

filetree

CodePudding user response:

The template is placed under posts/templates/posts/. If you enable the APP_DIRS, then it will look for all templates/ directories in all apps, but it is still placed under a posts/ directory, hence you access the template with:

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

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

CodePudding user response:

You need to specify the template directories in 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",
            ],
        },
    },
]

Since you have index.html is under the posts folder, the template path in views.py should be 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')
  • Related