Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...