Django 小部件模板覆盖不在项目模板目录中搜索.怎么修?
问题描述
我正在尝试覆盖 Django 1.11 中的内置小部件模板.在这方面,我似乎正在做文档所说的所有事情,但是对于小部件模板,Django 根本没有查看我的项目,并且我收到了 TemplateDoesNotExist 错误.
I am attempting to override a built in widget template in Django 1.11. I seem to be doing everything that the docs say to do in this regard, but for the widget templates, Django is not looking in my project at all, and I get a TemplateDoesNotExist error.
这是我的覆盖:
class MyFileWidget(widgets.FileInput):
template_name = 'myapp/my_file_widget.html'
模板肯定在那里.如果我将模板传递给渲染调用,它会发现它很好.问题是路径问题.从视图调用渲染时,它会检查以下内容:
The template is definitely there. If I pass the template to a render call, it finds it fine. Problem is an issue of paths. When calling render from a view, it checks the following:
projectroot/templates/myapp/my_file_widget.htmldjangoroot/forms/templates/myapp/my_file_widget.html
projectroot/templates/myapp/my_file_widget.html djangoroot/forms/templates/myapp/my_file_widget.html
当它在我的项目中找到模板时,它会渲染它.当我在上面的类中提供模板路径时,这不会发生.在这种情况下,它不会签入我的项目模板,该文件实际存在的位置,并开始签入 django 路径,它不存在.因此出现错误消息.
When it finds the template in my project, it renders it. This is NOT happening when I provide the template path in the class above. In that case, it does not check in my project templates, where the file actually exists, and begins checking in the django path, where it does not. Hence the error message.
所以我不知道为什么加载器会在渲染调用时检查我的项目模板,但是在查找小部件覆盖的template_name"时却没有这样做.有什么想法吗?
So I have no clue why this the loader would check my project templates on render calls, but then fail to do so when looking for the "template_name" of the widget override. Any ideas?
解决方案
默认情况下,FORM_RENDERER
设置默认为 'django.forms.renderers.DjangoTemplates'
.
By default, the FORM_RENDERER
setting defaults to 'django.forms.renderers.DjangoTemplates'
.
这会检查您应用的模板目录(例如 projectroot/myapp/templates/myapp/my_file_widget.html
),但不会检查您项目的模板目录(例如 projectroot/templates/myapp/my_file_widget.html
).
This checks your apps' templates directory (e.g. projectroot/myapp/templates/myapp/my_file_widget.html
), but it does not check your project's template directories (e.g. projectroot/templates/myapp/my_file_widget.html
).
如果您想使用与 TEMPLATES
设置相同的配置,则应使用 TemplatesSetting
渲染器.
If you want to use the same configuration as your TEMPLATES
setting, then you should use the TemplatesSetting
renderer.
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
您还需要更新您的 TEMPLATES
设置,以便 Django 仍然可以使用内置的小部件模板.最简单的方法是将 django.forms
添加到 INSTALLED_APPS
.有关更多信息,请参阅文档.
You will also need to update your TEMPLATES
setting so that Django can still use the built in widget templates. The easiest way to do this is to add django.forms
to INSTALLED_APPS
. See the docs for more info about this.
相关文章