gpt4 book ai didi

python - Django 。 TemplateDoesNotExist 在自定义小部件的情况下

转载 作者:太空狗 更新时间:2023-10-29 17:16:50 27 4
gpt4 key购买 nike

我正在尝试在 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 路径是从哪里来的?谢谢。

最佳答案

如果您想使用存储在项目“TEMPLATES”目录下某处的自定义小部件模板,请按照以下步骤操作:

a) 使用您在问题中提供的TEMPLATES设置

b) 在 settings.py

中设置 FORM_RENDERER
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

c) 将应用“django.forms”添加到 settings.py 中的“INSTALLED_APPS”列表

此外,请务必将自定义小部件模板相对于“TEMPLATES”目录的正确路径分配给自定义小部件的“template_name”属性。

关于python - Django 。 TemplateDoesNotExist 在自定义小部件的情况下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45844032/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com