2017-06-15 77 views
0

我最近试图学习Django作为我的一个私人项目。 当来到在模板中的第一章,Django的书推荐使用下面的代码片断Django Developments Template_DIRS设置失败

TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),) 

然而,当我打开文件setting.py我发现没有像“template_dir模板”设置在settings.py模板路径,但列表:

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),], 
    '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', 
     ], 
    }, 
}, 

]

相关的关键 “DIR” 的值,是一个空列表。所以我尝试填充上面显示的内容。

然后,代码的东西在views.py(所有进口已完成)与setting.py同一文件夹

def current_datetime(request): 
    now = datetime.datetime.now() 
    t = get_template("current_datetime.html") 
    html = t.render(Context({"current_date" : now})) 
    return HttpResponse(html) 

然后MKDIR模板,在模板文件夹中保存current_datetime.html

最后,运行project.and得到了在我的终端的消息:

警告: :(1_8.W001)的独立TEMPLATE_ *设置在Django 1.8中弃用>和TEMPLATES字典优先。您必须将以下设置的值放入您的默认模板字典:TEMPLATE_DIRS。

系统检查发现1个问题(0沉默)。 2017年6月15日 - 15:32:49 Django版本1.11.2,使用设置'mysite.settings' 在127.0.0.1:8000/处启动开发服务器使用CONTROL-C退出服务器。

当我打开Safari浏览器的地址(127.0.0.1:8000/time/),这里传来 错误消息:

enter image description here

任何帮助,请?

+0

浏览了很多,但发现没有什么帮助.. – Elias

+0

我的django版本:(1.11.2,u“final”,0)我的python版本:2。7 – Elias

+0

我一开始没有看到你的错误图像,你应该编辑你的文章,以正确地嵌入它或从中复制文本 – SebCorbin

回答

0

TEMPLATE_DIRS上有一个警告,因为只要确保在settings.py中没有TEMPLATE_DIRS变量并重新启动开发服务器即可。

那么对于错误,你实际上是使用一个上下文对象,而不是一个字典,你应该使用一个有用的快捷键https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#example

from django.shortcuts import render 

def current_datetime(request): 
    now = datetime.datetime.now() 
    return render(request, "current_datetime.html", { 
    'current_date' : now, 
    }) 
+0

谢谢,但我没有在setting.py中找到任何TEMPLATE_DIRS变量.... – Elias

+0

@SebCorbin他有TEMPLATE字典,不需要定义特定的TEMPLATE_DIRS –

0

我觉得你有BASE_DIR settings.py中的定义位置呈现模板所以使用如下

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [os.path.join(BASE_DIR, 'templates'),], 
    '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', 
     ], 
    }, 
}, 

DIRS应该有如下

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