【发布时间】:2018-02-01 07:09:31
【问题描述】:
我正在尝试在 Django 管理中创建自定义小部件。我创建了一个类:
class FroalaWYSIWYGTextareaWidget(django.forms.widgets.Textarea):
template_name = 'froala_wysiwyg.html'
然后是一个简单的模型形式:
class ArticleForm(django.forms.ModelForm):
class Meta:
fields = '__all__'
model = Article
widgets = {
'content': FroalaWYSIWYGTextareaWidget(),
}
这是我的设置:
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 错误:
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 是一个列表:
['/home/username/python/sitename/templates']
所以 Loader.get_template_sources() 很好用
但是对于这个自定义小部件,这个 loader.engine.dirs 只包含:
['/home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/forms/templates']
所以它只是忽略了设置中的DIRS 选项,而是使用表单/模板。它是 Django 的错误还是我必须更改设置中的某些内容?
我不明白这个django/forms/templates 路径来自哪里?
谢谢。
【问题讨论】:
标签: python django django-forms django-templates