django.template.exceptions.TemplateDoesNotExist: blogindex.html

xiaoxiao2021-02-28  37

django.template.exceptions.TemplateDoesNotExist: blog/index.html

错误原因:错把TEMPLATE写成TEMPLATE_DIRS

TEMPLATE_DIRS = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(My_Blog, 'templates').replace('\\', '/'),], 'APP_DIRS': True, # 如果'APP_DIRS': True,则直接在app的目录下寻找templates,这个是默认设置,所以最简单的是直接将templates文件夹放在app下。 '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', ], }, }, ] TEMPLATES = [# 整个setting只有此处不同。 { '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是Django 1.9 以前的语法,再1.9以后就不再支持了。


其他基础原理: 常见的习惯是载入一个模板、填充一个context 然后返回一个含有模板渲染结果的HttpResponse对象

template = loader.get_template('polls/index.html') context = RequestContext(request, { 'latest_question_list': latest_question_list, }) return HttpResponse(template.render(context))

为了方便书写,我们有一种更快捷的函数等你使用。

context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)

那问题来了,render和httpResponse俩产生的结果是一样的吧?

render()函数将请求对象作为它的第一个参数,模板的名字作为它的第二个参数,一个字典作为它可选的第三个参数。 它返回一个HttpResponse对象,含有用给定的context 渲染后的模板。

系统是如何根据’polls/index.html’找到模板的? Step1: create a directory called templates in your blog(我的app名是blog) directory.

Step2:Within the templates directory you have just created ,create another directory called blog,within that create a file called index.html.(大家都是这么做的,所以就约定俗成了。这时候你的html应该在 blog/templates/blog/index.html)

Step3: Django will look for templates in there.

转载请注明原文地址: https://www.6miu.com/read-600116.html

最新回复(0)