【问题标题】:django render template does not existdjango 渲染模板不存在
【发布时间】:2016-06-07 22:00:42
【问题描述】:

我正在使用linuxpython 3.4django 1.8.2pytmysql

在我的 virtualenv 中有:

db.sqlite3manage.pynew/templates/


settings.py:

首先我评论了'DIRS':[],

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',
            ],
        },
    },
 ]

然后添加这部分:

TEMPLATE_DIRS = (    
        '/home/niloofar/django/niloofar/new/templates',    
)

urls.py:

从 new.views 导入欢迎

urlpatterns = [
    url(r'^welcome', welcome),
]

views.py:

from django.shortcuts import render

def welcome(request):

    message = "welcome again:D"
    return render(request, 'base.html', {'message': message})

在templates目录下,有base.html文件:

<html>
 <body>
 <p>* {{ message }} *</p>
 </body>
 </html>

当我刷新页面时,它会打印错误:

异常类型:TemplateDoesNotExist

异常值:base.html

【问题讨论】:

  • base.html 的完整路径是什么?
  • /home/niloofar/django/niloofar/new/templates/base.html
  • 试试 $ ls -a /home/niloofar/django/niloofar/new/templates。你得到了什么?
  • 为什么使用TEMPLATE_DIRS?自 1.8 起已弃用。 docs.djangoproject.com/en/1.9/ref/settings/#template-dirs
  • 不要注释掉dirs,而是尝试将其设置为包含template_dirs中的目录的数组。

标签: python django django-templates


【解决方案1】:

试试这个,不需要评论 DIRS。 设置 TEMPLATE_DIRS 已弃用。见链接https://docs.djangoproject.com/en/1.9/ref/settings/#template-dirs

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(os.path.dirname(__file__), '..//', 'templates').replace('\\', '/')],
        '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',
            ],
        },
    },
]

【讨论】:

  • 如果您认为此解决方案对您有帮助,请用绿色标记批准它
  • 那些带有替换调用的东西是无稽之谈。不要做那样的事情。
  • @Sayes 感谢您的建议,我已经更新了我的答案
猜你喜欢
  • 2014-03-10
  • 2022-07-22
  • 1970-01-01
  • 2018-05-20
  • 2018-11-05
  • 1970-01-01
  • 2015-10-29
  • 2013-10-10
  • 2012-03-18
相关资源
最近更新 更多