Django. TemplateDoesNotExist in case of a custom widget
我正在尝试在Django管理员中创建自定义窗口小部件。我创建了一个类:
1 2 | class FroalaWYSIWYGTextareaWidget(django.forms.widgets.Textarea): template_name = 'froala_wysiwyg.html' |
然后是一个简单的模型形式:
1 2 3 4 5 6 7 | class ArticleForm(django.forms.ModelForm): class Meta: fields = '__all__' model = Article widgets = { 'content': FroalaWYSIWYGTextareaWidget(), } |
这是我的设置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_PATH, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.i18n', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] |
通常,一切正常,Django可以在我的/ templates /目录中找到模板,但是在使用此小部件的情况下,我出现500错误:
1 2 3 4 5 6 7 8 9 10 | TemplateDoesNotExist at /admin/article/article/1/change/ froala_wysiwyg.html Request Method: GET Request URL: http://127.0.0.1:8000/admin/article/article/1/change/ Django Version: 1.11.4 Exception Type: TemplateDoesNotExist Exception Value: froala_wysiwyg.html Exception Location: /home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/template/engine.py in find_template, line 148 Python Executable: /home/username/.virtualenvs/sitename/bin/python Python Version: 3.5.2 |
我调试了django.filesystem.loader,发现通常Loader.engine.dirs是一个列表:
所以Loader.get_template_sources()很好用
,但对于此自定义窗口小部件,该loader.engine.dirs仅包含:
因此它只是忽略设置中的
我不知道此
谢谢。
如果要使用存储在项目的" TEMPLATES"目录下某处的自定义窗口小部件模板,请执行以下步骤:
a)使用问题中提供的
b)在
中如下设置
1 | FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' |
c)将应用程序"
中的"
此外,请确保将自定义窗口小部件模板相对于"
肯定不是错误
I don't understand where does this django/forms/templates path come from?
您可以查看源代码,在其中可以看到
行
1 2 | [docs]class Textarea(Widget): template_name = 'django/forms/widgets/textarea.html' |
这是您的第一个问题。现在第二个
This renderer uses a standalone DjangoTemplates engine (unconnected to what you might have configured in the TEMPLATES setting). It loads templates first from the built-in form templates directory in django/forms/templates and then from the installed apps’ templates directories using the app_directories loader.
这对于您的表单窗口小部件类也是如此。为了使事情适合您的自定义小部件模板,您必须使用相同的术语指定路径,例如