为什么我不能加载index.html?

时间:2017-08-25 14:24:04

标签: python django

我收到了一个错误, 在/ polls /上的TemplateDoesNotExist 在我执行http://localhost:8000/polls/时轮询s / index.html。 Traceback说

回溯:

File "/Users/XXX/django/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  160.                 response = self.process_exception_by_middleware(e, request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  158.                 response = response.render()

File "/Users/XXX/django/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/Users/XXX/django/django/template/response.py" in rendered_content
  81.         template = self.resolve_template(self.template_name)

File "/Users/XXX/django/django/template/response.py" in resolve_template
  63.             return select_template(template, using=self.using)

File "/Users/XXX/django/django/template/loader.py" in select_template
  47.         raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)

Exception Type: TemplateDoesNotExist at /polls/
Exception Value: poll‌​s/index.html
Traceback:

File "/Users/XXX/django/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  160.                 response = self.process_exception_by_middleware(e, request)

File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
  158.                 response = response.render()

File "/Users/XXX/django/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/Users/XXX/django/django/template/response.py" in rendered_content
  81.         template = self.resolve_template(self.template_name)

File "/Users/XXX/django/django/template/response.py" in resolve_template
  63.             return select_template(template, using=self.using)

File "/Users/XXX/django/django/template/loader.py" in select_template
  47.         raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)

Exception Type: TemplateDoesNotExist at /polls/
Exception Value: poll‌​s/index.html

views.py就像

from django.shortcuts import render
from django.urls import reverse_lazy
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import resolve_url

def index(request):
    return render(request,'polls/index.html',{
        'questions': Question.objects.all(),
    })

def vote(request,pk):
    question = get_object_or_404(Question,pk=pk)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError,Choice.DoesNotExist):
        return render(request,'poll/detail.html',{
            'question':question,
            'error_message':"You didn't select a choice",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return redirect('index')
    return redirect('poll_results', pk)
    # pass

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

class FormTest(FormView):
   form_class = MyForm
   template_name = 'polls/form.html'
   success_url = reverse_lazy('polls:index')
form_test = FormTest.as_view()

class Detail(SingleObjectMixin,FormView):
    model = Question
    form_class = VoteForm
    context_object_name = 'question'
    template_name = 'polls/detail.html'

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super().post(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['question'] = self.object
        return kwargs

    def form_valid(self, form):
        form.vote()
        return super().form_valid(form)

    def get_success_url(self):
        return resolve_url('polls:results',self.kwargs['pk'])

detail = Detail.as_view()

urls.py是

from django.conf.urls import url
from django.views.generic import TemplateView
from . import views

app_name="polls"

    urlpatterns = [
        url(r'(?P<pk>\d+)/$', views.detail, name='poll_detail'),
        url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
        url(r'(?P<pk>\d+)/results$', views.results, name='poll_results'),
        url(r'^$',TemplateView.as_view(template_name='poll‌​s/index.html'),name='app_index'),
        url(r'^form$', views.form_test),
    ]

我真的无法理解为什么index.html无法加载。我认为这部分def索引(请求):views.py读取index.html ...那么,我该如何解决这个问题?

我的setting.py是

"""
Django settings for djangostudy project.

Generated by 'django-admin startproject' using Django 2.0.dev20170803012132.

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

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

import os

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


# 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 = '****************'

# SECURITY WARNING: don't run with debug turned on in production!
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',
    'bootstrap3',
]

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 = 'djangostudy.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',
                # 'app.apptemplates.load_setting',
            ],
            # 'libraries':{
            # 'my_templatetag': 'djangostudy.templates',
            #
            # }
        },
    },
]

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

WSGI_APPLICATION = 'djangostudy.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(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 = 'ja'

TIME_ZONE = 'Asia/Tokyo'

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/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

1 个答案:

答案 0 :(得分:0)

确保您的模板结构为:

project_root/
           templates/
                   polls/
                        index.html

它会起作用。

此外,请确保您对所有模板使用polls,我可以在一个视图中查看其polls,在另一个视图中,poll,使它们相同