如何在 Django 中覆盖外部应用程序模板?

2024-03-20

我尝试覆盖django-recaptcha模板没有任何运气。我究竟做错了什么? 我知道在 Django 中覆盖外部应用程序的模板 https://stackoverflow.com/questions/17918839/override-templates-of-external-app-in-django,但它已经过时了。谢谢!

django-recaptcha 文件结构

Lib/
--site-packages/
----captcha/
------templates/
--------captcha/
----------includes/
------------js_v2_checkbox.html

我的项目文件结构

project/
----templates/
--------captcha/
------------includes/
----------------js_v2_checkbox.html

设置.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

您有两个选择:

(1) 在您的设置中,重新排列 INSTALLED_APPS,如下所示:

INSTALLED_APPS = [
    ...
    'project',
    ...
    'captcha',
    ...
]

由于模板加载器将按照 INSTALLED_APPS 指定的顺序在应用程序的模板目录中查找,因此将首先找到您的模板。

or

(2) 列出 TEMPLATES[0]['IS'] 中的项目模板文件夹,如下所示:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
    },
]

由于 DIRS 在 APP_DIRS 之前被搜索,因此您的模板将首先被找到。

参考:

https://docs.djangoproject.com/en/3.0/howto/overriding-templates/ https://docs.djangoproject.com/en/3.0/howto/overriding-templates/

另一种可能的解决方案

我现在注意到captcha/includes/js_v2_checkbox.html包含在captcha/widget_v2_checkbox.html.

我不确定具体什么时候会发生什么widget_v2_checkbox.html从验证码模块加载...所以我会复制“包括”widget_v2_checkbox.html以及项目的模板文件夹中。

您可能还决定将完整的“templates/captcha”文件夹内容复制到您的项目中,以保持一致性。

升级验证码模块时,请留意这些模板未来可能发生的变化。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Django 中覆盖外部应用程序模板? 的相关文章

随机推荐