用django访问模板时,总是出现 500 错误。开始想到是不是import不足,但是看的各路教程都是
from django.shortcuts import render_to_response
就足够,我还添加了
from django.http import HttpResponsefrom django.shortcuts import render
虽然只是最简单的返回
def userinfo(request):
try:
return render_to_response('userinfo.html',)
except Exception,e :
print str(e)
测试也不是urls.py的问题。又写了另一个更简单的html,完全没有django模板语句,也不行。看到控制台打出了
userinfo.html
[04/May/2014 23:10:04] "GET /login HTTP/1.1" 500 27
这样的东西,为什么会有html的名字?想到是不是setting.py的问题,把render_to_response的参数名命名成一个不存在的html名(userinfo2.html),果然也是server error 500,打印是
userinfo2.html
[04/May/2014 23:10:04] "GET /login HTTP/1.1" 500 27
setting.py有TEMPLATE_DIRS元组,添加了一个'/template', (注意逗号)的文件夹,目录结构是:
G:\works\3
|----mywork
|----templates 模板文件夹
|-----userinfo.html 模板
|----setting.py setting.py和模板文件夹同级
|----__init__.py
|----urls.py
|----wsgi.py
|----- ....
|---manage.py
调了一晚上啊。。。最后看到setting.py的template_dir里的注释,吐一口老血
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
好吧,原来是必须要用绝对地址啊,而不是相对地址啊,改成
TEMPLATE_DIRS = (
'G:/works/3/mywork/templates',
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
成功。。。
转到SAE上,相同的目录结构的话(manage.py在根目录,和index.wsgi与config.yaml在一个目录下),改成
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'./mywork/templates',
)
就可以了。。。。。
相对地址、绝对地址真心郁闷啊
另,看到有些也是 500 的问题解决方案,也是setting.py的问题,如 ALLOWED_HOSTS ,可访问django的主机,默认是 ['*'] 即所有,有时候会改成['localhost'],在上线之后就会有 error 500 ,改成对应的域名即可,比如 ['www.wolegequ.com'] 云云