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

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.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值