【问题标题】:Django: TemplateDoesNotExist. Tried numerous different things alreadyDjango:模板不存在。已经尝试了许多不同的东西
【发布时间】: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 viewsfrom . import views 命令将是您在 polls/urls.py 中放入的内容。
  • @Chris McGinlay 我这样做了,现在我收到一条错误消息,上面写着“TemplateDoesNotExist at /polls/”,下面列出了“index.html, polls/question_list.html”。我刚刚意识到我没有那些 html 文件,所以它正在调用实际上不存在的文件哈哈。我会创建它们,看看是否能解决问题:)

标签: python django django-templates django-views


【解决方案1】:

我认为 TEMPLATES 设置中的模板 DIRS 应该是原来的样子:

'DIRS': [os.path.join (BASE_DIR,'templates')],

拥有'APP_DIRS': True, 应该会从您的所有应用中提取模板。

当您在浏览器中收到可怕的“TemplateDoesNotExist at ...”消息时,查看模板加载器事后分析可能会有所帮助:

Django 尝试按以下顺序加载这些模板:

希望这会提供一些线索 - 你能把它贴在这里吗?

【讨论】:

  • +1 'Django 尝试按此顺序加载这些模板' 应该包含解决问题所需的信息。
  • @ChrisMcGinlay 我将“DIRS”更改为只有“模板”。基尔
【解决方案2】:

您不必将 polls 目录包含在您的 DIRS 设置中。 Django 会找到它,因为您将 APP_DIRS 设置为 True

所以你可以把DIRS改回。

'DIRS': [os.path.join(BASE_DIR,'templates')],

现在,请注意polls/templates 内应该有一个polls 目录,例如详细信息模板应位于polls/templates/polls/details.html

最后,坚持本教程,并将投票视图保留在 polls/views.py。拥有两个相似的文件 forumtest/views.pypolls/views.py 会让事情变得非常混乱。

【讨论】:

  • 我已经在 'polls/templates' 文件中有一个 polls 目录。是的,我同意你的观点,一旦我注意到它,我就会感觉到有问题。问题是教程并不清楚放置视图文件:(
  • 要解决导入错误,请显示您的根 urls.py。请注意,您应该拥有template_name = 'polls/index.html' 以与您的其他视图保持一致。
【解决方案3】:

遇到同样的问题,在 finder 中或在文本编辑器/IDE 之外打开该文件并重命名它,同时检查扩展名。

【讨论】:

    【解决方案4】:

    试试这个:

    BASE_DIR = os.path.dirname(os.path.dirname(__file__))
    
    INSTALLED_APPS = (
    ...
        'polls',
    )
    
    TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
    
    TEMPLATE_DIRS = (
        TEMPLATE_PATH,
    )
    

    你的模板应该在“polls/templates”目录或主“templates”目录中

    【讨论】:

    • 这些是旧模板设置。 OP 使用的是 Django 1.8,它有一个新的 TEMPLATES 设置。
    • 我在 django 1.8.4 中使用它没有任何问题。您至少可以尝试一下,看看问题是否已解决,然后下一步就是迁移到新配置。
    • 是的,你可以使用 1.8 中的旧设置,但你不应该混合新旧设置。由于 OP 已经在使用TEMPLATES,因此他们不会通过切换到旧设置来获得任何收益。
    • 我同意。试试这个:'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, -> 这进入 TEMPLATES 中,如 Alasdair 所示:)
    • @Chris McGinlay 我像你说的那样更改了“DIRS”部分。我将在原始帖子的编辑中包含 Loader 事后分析。
    猜你喜欢
    • 2020-06-14
    • 2019-07-13
    • 2020-08-22
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多