Django widget template override does not search in the project template directory. How to fix?

◇◆丶佛笑我妖孽 提交于 2019-12-17 18:18:36

问题


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.

Here's what I have for the override:

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.html djangoroot/forms/templates/myapp/my_file_widget.html

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.

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?


回答1:


By default, the FORM_RENDERER setting defaults to 'django.forms.renderers.DjangoTemplates'.

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).

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'

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.



来源:https://stackoverflow.com/questions/46835633/django-widget-template-override-does-not-search-in-the-project-template-director

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!