【问题标题】:TemplateDoesNotExist at /search/ in Django 2.0.2Django 2.0.2 中 /search/ 的 TemplateDoesNotExist
【发布时间】:2018-07-17 14:41:26
【问题描述】:

当我尝试执行该函数时,我得到 (TemplateDoesNotExist at /search/) 我的模板文件夹位于 C:\Users\Rafik\Documents\myproject\env_mysite\Scripts\mysie\books\templates python 代码运行良好,但显示 TemplateDoesNotExist

views.py:

def 搜索(请求):

error = False

if 'q' in request.GET:

    q = request.GET['q']

    if not q:

        error = True

    elif len(q) > 20:

        error = True

    else:

        books = Book.objects.filter(title__icontains=q)

        return render(request, 'search_results.html', {'books': books, 'query': q})

return render(request, 'search_form.html', {'error': error})

应用程序/urls.py:

从 django.conf.urls 导入 url

从书籍导入视图

urlpatterns = [

url(r'^search-form/$', views.search_form),
url(r'^search/$', views.search)

]

模板设置.py

模板 = [

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

]

【问题讨论】:

标签: python-3.x django-2.0


【解决方案1】:

作为作者,我是 stackoverflow 的新手,所以请原谅我没有在这里使用适当的标记。我在阅读 Django 2.0 教程时遇到了同样的错误(更具体地说:在 Tutorial03 中,从 loader.get_template() 切换到 shortcuts.render() 之后)。以下解决方案最终证明对我有用:

  • 在我的 settings.py 的 TEMPLATES 部分中,DIRS 仍然是一个空列表,并且 APP_DIRS 设置为 True。
  • 在 render() 语句中,指定模板时没有路径部分,例如渲染(请求,'index.html',上下文)
  • 模板文件必须直接位于 app/templates 目录中(而不是 /app/templates/app)

我的环境是 Windows 10(和 cygwin)下的 Django 2.0.2 和 CPython 3.6.4。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 2011-06-13
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多