Traceback Error in Django Test Client

In “Writing Your First Django App, Part 5”, in the section “Django Test Client” I am getting the following Traceback Error when entering the command response = client.get(reverse("polls:index") in the shell:

Internal Server Error: /polls/
Traceback (most recent call last):
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 220, in _get_response
    response = response.render()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 114, in render
    self.content = self.rendered_content
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 90, in rendered_content
    template = self.resolve_template(self.template_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 72, in resolve_template
    return select_template(template, using=self.using)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: polls/index.html, polls/question_list.html
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 927, in get
    response = super().get(path, data=data, secure=secure, headers=headers, **extra)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 457, in get
    return self.generic(
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 609, in generic
    return self.request(**r)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 891, in request
    self.check_exception(response)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\test\client.py", line 738, in check_exception
    raise exc_value
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 220, in _get_response
    response = response.render()
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 114, in render
    self.content = self.rendered_content
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 90, in rendered_content
    template = self.resolve_template(self.template_name)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", line 72, in resolve_template
    return select_template(template, using=self.using)
  File "C:\Users\duysa\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template
    raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: polls/index.html, polls/question_list.html

When I enter response.status_code after this, it still returns 404 and not the expected 200

Here is my models.py:

import datetime

from django.db import models
from django.utils import timezone

# Create your models here.
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")
    def __str__(self):
        return self.question_text
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now
    def test_was_published_recently_with_old_question(self):
        time = timezone.now() - datetime.timedelta(days=1, seconds=1)
        old_question = Question(pub_date=time)
        self.assertIs(old_question.was_published_recently(), False)
    def test_was_published_recently_with_recent_question(self):
        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)
        recent_question = Question(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)
    

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

This indicates one of a couple of different issues -

  • Your TEMPLATES section in your settings isn’t correct.
  • Those referenced template files don’t exist
  • Those files aren’t in the right directory

If you’d like more specific assistance with this, please post the contents of your settings.py file, along with identifying the full directory path where your project resides and where the template files are located relative to that. (Also make sure you don’t have a duplicate definition for the TEMPLATES settings.)

Here is my Settings.py file:

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 4.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-fd(@wl!=&fa^hga-sr8nmnz3cgu#^a04+k(j6xj^3!@p@1(#z9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    "polls.apps.PollsConfig",
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

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

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UCT'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Project resides in the following directory: “D:\DjangoTutorial1Attempt2\mysite”, with template files located in “D:\DjangoTutorial1Attempt2\mysite\polls\templates”

This directory identifies the “base” directory for template references.

If your render function is specifying polls/index.html, then the template should reside in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\polls\index.html”

That was it. The index.html was residing in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\index.html” , when it should have been located in “D:\DjangoTutorial1Attempt2\mysite\polls\templates\polls\index.html”

Thank you for the help.