Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

python - TemplateDoesNotExist: polls/question_detail.html Django tutorial

Studied the tutorial up to the seventh part. Everything was fine until I decided to launch my application. After launch, I added a multiple choice question. The error occurs after I click on a question to answer it. Long searches for an answer did not bring any results. Please help.

I get this error:

TemplateDoesNotExist at /polls/1/
polls/question_detail.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/1/
Django Version: 4.0.dev20210118085850
Exception Type: TemplateDoesNotExist
Exception Value:    
polls/question_detail.html
Exception Location: c:usersmranddjangodjangoemplateloader.py, line 47, in select_template
Python Executable:  C:UsersmrandAnaconda3envsmysitepython.exe
Python Version: 3.8.6
Python Path:    
['C:\Users\mrand\mysite',
 'C:\Users\mrand\Anaconda3\envs\mysite\python38.zip',
 'C:\Users\mrand\Anaconda3\envs\mysite\DLLs',
 'C:\Users\mrand\Anaconda3\envs\mysite\lib',
 'C:\Users\mrand\Anaconda3\envs\mysite',
 'C:\Users\mrand\Anaconda3\envs\mysite\lib\site-packages',
 'c:\users\mrand\django',
 'C:\Users\mrand\Anaconda3\envs\mysite\lib\site-packages\win32',
 'C:\Users\mrand\Anaconda3\envs\mysite\lib\site-packages\win32\lib',
 'C:\Users\mrand\Anaconda3\envs\mysite\lib\site-packages\Pythonwin']
Server time:    Wed, 27 Jan 2021 01:15:15 +0300

Traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/

Django Version: 4.0.dev20210118085850
Python Version: 3.8.6
Installed Applications:
['polls.apps.PollsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed 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']

Template loader postmortem
Django tried loading these templates, in this order:

Using engine django:
    * django.template.loaders.filesystem.Loader: C:Usersmrandmysiteemplatespollsquestion_detail.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: C:Usersmrandmysitepollsemplatespollsquestion_detail.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: c:usersmranddjangodjangocontribadminemplatespollsquestion_detail.html (Source does not exist)
    * django.template.loaders.app_directories.Loader: c:usersmranddjangodjangocontribauthemplatespollsquestion_detail.html (Source does not exist)



Traceback (most recent call last):
  File "c:usersmranddjangodjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "c:usersmranddjangodjangocorehandlersase.py", line 204, in _get_response
    response = response.render()
  File "c:usersmranddjangodjangoemplate
esponse.py", line 105, in render
    self.content = self.rendered_content
  File "c:usersmranddjangodjangoemplate
esponse.py", line 81, in rendered_content
    template = self.resolve_template(self.template_name)
  File "c:usersmranddjangodjangoemplate
esponse.py", line 63, in resolve_template
    return select_template(template, using=self.using)
  File "c:usersmranddjangodjangoemplateloader.py", line 47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)

Exception Type: TemplateDoesNotExist at /polls/1/
Exception Value: polls/question_detail.html

Views.py

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

from django.http import HttpResponse
from django.template import loader

from .models import Question


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))
# Leave the rest of the views (detail, results, vote) unchanged
from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question
# ...
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

from django.shortcuts import get_object_or_404, render

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question
import datetime
from django.utils import timezone

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

 
    def get_queryset(self):
        """
        Return the last five published questions (not including those set to be
        published in the future).
        """
        return Question.objects.filter(
            pub_date__lte=timezone.now()
    ).order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'


def vote(request, question_id):
    ... # same as above, no changes needed.

class DetailView(generic.DetailView):
    ...
    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

Settings.py

import os
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/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-&6_7o3ob-kr=@!hoyu&-&8t8+t7r5_-9ejnz4lrehwvwd5=i+a'

# 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': [os.path.join(BASE_DIR, 'templates')],
        '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/dev/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/dev/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/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Europe/Moscow'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

#TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

Urls.py

from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
]

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Update <a href="https://i.stack.imgur.com/V2Jis.png" rel


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So Django is searching for the template named question_detail.html in these directories:

C:Usersmrandmysiteemplatespollsquestion_detail.html

C:Usersmrandmysitepollsemplatespollsquestion_detail.html 

c:usersmranddjangodjangocontribadminemplatespollsquestion_detail.html

c:usersmranddjangodjangocontribauthemplatespollsquestion_detail.html

and it can not found.

Make sure you put your template in the right place. If nothing changed, try to rename your template name from polls/detail.html to polls/question_detail.html in your view:

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/question_detail.html', {'question': question})
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/question_detail.html'

Updated Depending on your dirs, pretty sure the problem is because of DIRS setting in settings.url. Change 'DIRS': [os.path.join(BASE_DIR, 'templates')], to 'DIRS': [],


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...