我正在尝试在django中加载模板。我创建了一个名为current_date.html的文本文件,并在文件
中输入"It is now {{current_date}}."
并将其放在模板目录
中C:\Users\reza\env_mysite\lib\site-packages\django\contrib\admin\templates
然后在视图中我写下了代码块:
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse, Http404
import datetime
def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date':now}))
return HttpResponse(html)
和我输入的urlpatterns内部:
url(r'^time/$', current_datetime)
在settings.py文件中,在DEDS中键入:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
下次我输入
'DIRS': ['C:\Users\reza\env_mysite\lib\site-
packages\django\contrib\admin\templates']
但是在这两种情况下我都收到了TemplateDoesNotExist错误以及以下详细信息
Request Method: GET
Request URL: http://127.0.0.1:8000/time/
Django Version: 1.11.2
Python Version: 3.6.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.filesystem.Loader: C:\Users\reza\templates\current_datetime.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\reza\env_mysite\lib\site-packages\django\contrib\admin\templates\current_datetime.html (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\Users\reza\env_mysite\lib\site-packages\django\contrib\auth\templates\current_datetime.html (Source does not exist)
您能告诉我我的代码有什么问题
答案 0 :(得分:2)
你绝对不应该把自己的模板放在Django的任何目录中。您的代码应该是完全独立的。
您应该在项目中创建自己的templates
目录并将模板放在那里;那么你的第一次尝试os.path.join(BASE_DIR,'templates')
就行了。
答案 1 :(得分:0)
其余错误如下:
Traceback:
File "C:\Users\reza\env_mysite\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\reza\env_mysite\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\reza\env_mysite\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\reza\mysite\views.py" in current_datetime
11. t = get_template('current_datetime.html')
File "C:\Users\reza\env_mysite\lib\site-packages\django\template\loader.py" in get_template
25. raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /time/
Exception Value: current_datetime.html
答案 2 :(得分:0)
您说您已将此新模板var getScriptOnce = (function(url, callback) {
var scriptArray = []; //array of urls
return function (url, callback) {
//the array doesn't have such url
if (scriptArray.indexOf(url) === -1){
if (typeof callback === 'function') {
return $.getScript(url, function(script, textStatus, jqXHR) {
scriptArray.push(url);
callback(script, textStatus, jqXHR);
});
} else {
return $.getScript(url, function(){
scriptArray.push(url);
});
}
}
//the file is already there, it does nothing
//to support as of jQuery 1.5 methods .done().fail()
else{
return {
done: function () {
return {
fail: function () {}
};
}
};
}
}
}());
/*#####################################################################*/
/*#####################################################################*/
//TEST - tries to load the same jQuery file twice
var jQueryURL = "https://code.jquery.com/jquery-3.2.1.js";
console.log("Tries to load #1");
getScriptOnce(jQueryURL, function(){
console.log("Loaded successfully #1")
});
//waits 2 seconds and tries to load again
window.setTimeout(function(){
console.log("Tries to load #2");
getScriptOnce(jQueryURL, function(){
console.log("Loaded successfully #2");
});
}, 2000);
放在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
目录中。这是Django包的一部分,应该包含两个目录current_date.html
和C:\Users\reza\env_mysite\lib\site-packages\django\contrib\admin\templates
。是否有可能将新模板放在其中一个内部文件夹中,例如admin/
文件夹?
如果有,那么您应该在视图中更新对registration/
的调用,使其如下所示:
admin/
请注意,您不符合此处的最佳做法,但这确实是一个单独的问题。一些建议是将这个新模板转移到您自己的应用程序的get_template()
目录中(对安装的软件包进行修改通常不是一个好主意),您还应该使用django.shortcuts.render
,这会减少您必须编写/管理的代码量:
def current_datetime(request):
now = datetime.datetime.now()
t = get_template('admin/current_datetime.html') # note updated path
html = t.render(Context({'current_date':now}))
return HttpResponse(html)