Django 常规视图无法加载并引发TemplateDoesNotExist错误
我正在尝试使用Django中的通用视图。这是Django官方网站教程的一部分。这个问题我已经讨论了几个小时了,不知怎么的,这个网站和其他网站上的其他答案似乎并没有解决我的问题 index.html文件作为localhost:8000/polls成功加载,但之后的任何操作都会抛出TemplateDoesNotExist错误。我不知道为什么当它试图加载一个通用视图时,它失败了。我还尝试删除index.html文件,但仍然无法加载通用视图 我可能会在这里列出所有关注的问题: My settings.py文件:Django 常规视图无法加载并引发TemplateDoesNotExist错误,django,django-templates,Django,Django Templates,我正在尝试使用Django中的通用视图。这是Django官方网站教程的一部分。这个问题我已经讨论了几个小时了,不知怎么的,这个网站和其他网站上的其他答案似乎并没有解决我的问题 index.html文件作为localhost:8000/polls成功加载,但之后的任何操作都会抛出TemplateDoesNotExist错误。我不知道为什么当它试图加载一个通用视图时,它失败了。我还尝试删除index.html文件,但仍然无法加载通用视图 我可能会在这里列出所有关注的问题: My settings.p
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = ( "C:/Django/mysite/templates/polls/", )
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'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'pankaj29',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
My views.py文件是:
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
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."""
return Question.objects.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):
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.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
我的URL.py文件是:
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
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."""
return Question.objects.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):
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.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
从django.url导入路径
从…起导入视图
应用程序名称='polls'
URL模式=[
路径(“”,views.IndexView.as_view(),name='index'),
路径('/',views.DetailView.as_view(),name='detail'),
路径('/results/',views.ResultsView.as_view(),name='results'),
路径('/vote/',views.vote,name='vote'),
]
我的文件结构是:
提前谢谢 问题是我不清楚这个概念。我认为泛型视图是指Django中内置的一组视图,很像Django中内置的管理页面。但实际上,通用视图只是针对应用程序的特定通用视图,而不是任何内置视图。把这个问题留给有同样问题的人。你没有
results.html
或detail.html
TEMPLATE\u DIRS
和TEMPLATE\u loader
自从Django 1.8以来就没有使用过,我会避免使用任何使用它们的书籍或教程,因为它们已经过时了。您可以从设置中删除它们,因为它们不会产生任何效果。在堆栈溢出中发布密码和密钥不是一个好主意。请确保在部署站点之前更改这些值,如果您在其他任何地方使用该密码,请将其更改为更难破解的更长密码。但正如Iain所说,您只有一个索引模板,因此不清楚您希望详细信息或结果页如何工作。@Alasdair感谢您的建议。我会记住的。