TemplateDoesNotExist at /hello/ Django error



我是 django python 的初学者。尽管我的模板具有正确的目录,但我仍收到上述错误。

我的 view.py 是这样的。

from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
def hello(request):
    return render(request,"C:/Users/Vivek/myproject/myapp/template/hello.html",{})

我正在问候.html在 C:\Users\Vivek\myproject\myapp\template

以下是我得到的错误。

TemplateDoesNotExist at /hello/
C:/Users/Vivek/myproject/myapp/template/hello.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/hello/
Django Version: 1.11.10
Exception Type: TemplateDoesNotExist
Exception Value:    
C:/Users/Vivek/myproject/myapp/template/hello.html

这是链接模板的糟糕方法。而是检查设置文件并定义操作系统绝对路径。它将看起来像这样:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

将代码从

return render(request,"C:/Users/Vivek/myproject/myapp/template/hello.html",{})

对此

return render(request,"hello.html",{})

它应该有效。

Django 这样做的方法是在设置文件中定义模板的目录

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

因此,只需将此行添加到您的模板设置中,您就可以开始了。

Django 会自动在你传递的目录中搜索模板,你只需要在 render 方法中给出模板名称。

最新更新