Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TemplateDoesNotExist at /polls/

I have been trying out the Django tutorialDjango Tutorial Page 3 and encountered this error

"TemplateDoesNotExist at /polls/ " .

I assume the problem is with my code pointing the templates file index.html. This is my file structure for index.html: mysite/polls/templates/polls. I am copying my settings.py and views.py here.

settings.py

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

views. Py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader

from polls.models import Poll

# Create your views here.

#def index(request):
    #return HttpResponse("Hello, world. You are at the poll index.")

def index(request):
    latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = RequestContext(request, {
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(template.render(context))

def detail(request,poll_id):
    return HttpResponse("You're looking at the results of the poll %s." % poll_id)

def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request,poll_id):
    return HttpResponse("You're voting on poll %s." % poll_id)

Can someone look into it and help me to solve this error. Any help would be appreciated. This is the traceback `Environment:

Request Method: GET
Request URL: http://localhost:8000/polls/

Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'polls')
Installed Middleware:
('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')

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)



Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
  14.     template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
  138.     template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
  131.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`

Please let me know if i missed out anything that would give a more clear picture. Thanks in advance.

Settings.py """

Django settings for mysite project.

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

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

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='

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

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

MIDDLEWARE_CLASSES = (
    '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'

WSGI_APPLICATION = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
    }
}

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]


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

STATIC_URL = '/static/'
like image 800
rv_k Avatar asked May 15 '14 16:05

rv_k


2 Answers

Whoa whoa whoa. Let's not advocate non re-usability of apps.

For templates that don't fit anywhere else (usually your base template, maybe some partial templates like form includes, etc.), it's fine to put them in your root templates directory (ie. /path/to/project/templates/base.html). You would refer to them in a view for rendering as base.html.

For other templates, I would advise you put them in the directory of the app that contains the views that render to those templates. For example, your polls index would go somewhere such as /path/to/project/polls/templates/polls/index.html.

The extra polls directory may look redundant there, but the reason is that the django template loader will (logically) dump all your templates in one directory. So we use the second polls directory to differentiate between multiple index.html templates that may exist. So in your view, you would use polls/index.html as normal.

The reason that this is a Good Thing is that it makes your apps more easily reusable. Written one polls app? You've written them all. If you do this, and also keep your app specific static files (js, css, images, etc.) in your app's static directory, and have a urls.py for each app, generally all you will need to do to move your app from one project to another is copy the directory, add to the new project's INSTALLED_APPS, and include the urls from your base urls.py. And of course, modify the app in any way you need to for the new project.

It also means if you're using an editor with sidebar navigation (most of them, these days), you don't have to scroll all the way down to your templates to find the template for that app. When you start working on large projects this gets tedious, fast.

The only thing to remember in using this technique is that you must have django.template.loaders.app_directories.Loader in your TEMPLATE_LOADERS setting. This is the default so you usually won't have to worry about it.

There is a nice guide for this in the django docs: https://docs.djangoproject.com/en/1.7/intro/reusable-apps/

To answer the question you actually asked:

Your index.html should be here: C:\Python34\mysite\polls\templates\polls\index.html. If it isn't, that's what you're doing wrong.

On a related note, you probably shouldn't have your project in the Python directory.

like image 73
Tom Carrick Avatar answered Sep 27 '22 22:09

Tom Carrick


Try to put template folder in projects root folder:

mysite/templates/polls/index.html

Explanation

Your template dirs is

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

It containts only one directory: /path/to/your/project/templates

And your index.html located in /path/to/your/project/polls/templates

Update

As you say it doesn't work with templates stored in mysite/templates/polls/index.html let's try this way:

go to mysite and run

python manage.py shell

to run interactive interpreter with mysite as context. Then run this:

from settings import TEMPLATE_DIRS
print TEMPLATE_DIRS

it will output something like

('/var/www/mithril/templates/', '/home/dmitry/proj/mithril/templates/')

Django uses this directories to find your templates. Thus you should put directory polls/ in folder from TEMPLATE_DIRS.

like image 23
Dmitry Loparev Avatar answered Sep 27 '22 23:09

Dmitry Loparev