djangodjango-templates

Django Cannot load a template in the template path of INSTALLED_APPS


I'm using python 3.5.2 and django 1.11.6. My OS is win10. I cannot load my template in the installed_app path.

I've created a file at "polls/template/polls/index.html". I've also add the app, polls, into INSTALLED_APPS and set APP_DIRS in TEMPLATES to True. I cannot figure out why django won't load the template in the INSTALLED_APPS template folder as the tutorial told me.

I used the following code snippet to load the template in my view.

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

I got this TemplateDoesNotExist. I'm wondering that why django doesn't search the path, "polls/template". The paths searched by django are as following.

My INSTALLED_APPS is as following.

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

My TEMPLATES setting is as following.

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

Solution

  • Your template directory is wrong. It should be polls/templates/polls/index.html - templates instead of template. From the tutorial:

    First, create a directory called templates in your polls directory. Django will look for templates in there.

    Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html.