我已经尝试了几种方法,但都没有运气。如果我尝试像这样呈现我的视图:
from django.shortcuts import render
from django.template import loader
def index(request):
render(request, loader.get_template('index.html'))
我收到此错误:
TemplateDoesNotExist at /
如果我将代码更改为:
from django.http import HttpResponse
from django.template.loader import render_to_string
def index(request):
content = render_to_string('index.html')
HttpResponse(content)
它实际上找到了模板并呈现它(content
设置为呈现的 html),但我现在收到此错误:
ValueError at /
The view home.controller.index didn't return an HttpResponse object.
这是我的文件夹结构和设置:
myProject/
settings.py
home/
controller.py
urls.py
models.py
templates/
home/
index.html
在我的 setting.py 文件中,我有:
SITE_ROOT = os.path.dirname(os.path.realpath(__name__))
TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'home/templates/home'), )
INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.staticfiles',
'gunicorn',
'home'
)
我已经尝试了多种变体,TEMPLATE_DIRS
但假设只是正确地选择它,因为我已经home
添加了我认为的应用程序。有人知道这里发生了什么吗?
更新
一系列事情解决了这个问题。首先return
需要声明(doh),我想我正在混合如何呈现模板的示例。无需导入加载器或手动渲染。这就是我最终得到的结果:
from django.shortcuts import render
def index(request):
return render(request, 'home/index.html')
感谢@lalo 和@Rao 为我指明了正确的方向。