詹戈。如果是自定义窗口,则模板不存在

2024-05-15 21:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在Django管理中创建一个自定义小部件。我创建了一个类:

class FroalaWYSIWYGTextareaWidget(django.forms.widgets.Textarea):
    template_name = 'froala_wysiwyg.html'

然后是一个简单的模型形式:

^{pr2}$

以下是我的设置:

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发现通常装载机.engine.dirs是一个列表: ['/home/username/python/sitename/templates'] 所以Loader.get_template_源()效果很好

但是对于这个自定义小部件发动机驱动仅包含: ['/home/username/.virtualenvs/sitename/lib/python3.5/site-packages/django/forms/templates']

所以它只是忽略设置中的DIRS选项,而是使用表单/模板。是Django的bug还是我必须更改设置? 我不明白这条路径从何而来? 谢谢。在


Tags: djangohome部件htmlcontextarticleusernametemplate
2条回答

当然不是虫子

I don't understand where does this django/forms/templates path come from?

您可以在source code处查看该行

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

对于窗体小部件类也是如此。要使自定义小部件模板正常工作,必须使用相同的术语指定路径,如app_name/forms/widget/textarea.html

如果要使用存储在项目“TEMPLATES”目录下某个地方的自定义小部件模板,请执行以下步骤:

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

b)在settings.py中设置FORM_RENDERER

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

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

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

相关问题 更多 >