【发布时间】:2015-08-26 22:56:09
【问题描述】:
我知道这显然是一个常见问题,但我已经浏览了一堆示例,但找不到解决方案。
我正在做django1.8的教程。所以我不确定这是否是一个小故障。我尝试将我的模板文件移动到多个位置,但到目前为止没有任何效果。
我的项目结构是这样的:我的项目名为“forumtest”,它位于名为“venv”的虚拟环境中。 Forumtest 有一款名为“民意调查”的应用程序。我将“templates”文件夹存储在“forumtest”的根目录中,但我只是将它移到了“polls”目录中。但是,我得到了相同的结果。
截至目前,我的 settings.py 文件如下所示:
"""
Django settings for forumtest project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
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/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$nnwkm0ln!$77m1n!%wv-5)k_rhs=-p-)xr-c-+m985w3jq#*='
# 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',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'forumtest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join (BASE_DIR,'C:/Desktop/Users/Owner/forumtest/polls/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 = 'forumtest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'forumtest',
'USER': 'admin',
'PASSWORD': 'aldotheapache12',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
“DIRS”部分如下所示:
'DIRS': [os.path.join (BASE_DIR,'C:/Desktop/Users/Owner/forumtest/polls/templates')],
以前是这样的:
'DIRS': [os.path.join (BASE_DIR,'templates')],
我的视图文件,存储在“forumtest”目录下,如下所示:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice,Question
# Create your views here.
class IndexView(generic.ListView):
template_name = '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):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except(KeyError,Choice.DoesNotExist):
#redisplay the question voting form
return render(request,'polls/detail.html',{
'question':p,
'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=(p.id,)))
我在“polls”下有完全相同的视图文件,除了这一行(我知道这可能是一个问题:
from .models import Choice,Question
请告诉我如何解决这个问题。谢谢大家!
编辑:根据@Chris McGinlay 的要求,这是模板加载器事后分析:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Users\Owner\Desktop\venv\forumtest\templates\index.html, polls\question_list.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Users\Owner\Desktop\venv\lib\site-packages\django\contrib\admin\templates\index.html, polls\question_list.html (File does not exist)
C:\Users\Owner\Desktop\venv\lib\site-packages\django\contrib\auth\templates\index.html, polls\question_list.html (File does not exist)
C:\Users\Owner\Desktop\venv\forumtest\polls\templates\index.html, polls\question_list.html (File does not exist)
感谢你们所有的cmets,伙计们!
编辑:所以我删除了位于“forumtest/forumtest”目录下的额外视图文件,现在我收到一个错误提示
cannot import name 'views'
:(
编辑:@Alasdair 这是根 urls.py 文件:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
【问题讨论】:
-
根 urls.py 中是否出现“无法导入名称 'views'”错误?我怀疑确实如此,因为你有
from . import views。点表示从与 urls.py 文件相同的目录导入,但如果你看你会发现你的 views.py 文件不在那个目录中,它是(或应该是)在 polls/views.py 中,所以您应该在根 urls.py 中使用from polls import views。from . import views命令将是您在 polls/urls.py 中放入的内容。 -
@Chris McGinlay 我这样做了,现在我收到一条错误消息,上面写着“TemplateDoesNotExist at /polls/”,下面列出了“index.html, polls/question_list.html”。我刚刚意识到我没有那些 html 文件,所以它正在调用实际上不存在的文件哈哈。我会创建它们,看看是否能解决问题:)
标签: python django django-templates django-views