How to override external app template in Django?

Viewed 776

I tried overriding a django-recaptcha template without any luck. What am I doing wrong? I am aware of Override templates of external app in Django, but it is outdated. Thanks!

django-recaptcha file structure

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

my project file structure

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

settings.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',
            ],
        },
    },
]
2 Answers

You have two options:

(1) In your settings, rearrange INSTALLED_APPS as follows:

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

since the template loader will look in the app’s templates directory following the order specified by INSTALLED_APPS, you're template will be found first.

or

(2) List project's templates folder in TEMPLATES[0]['DIRS'] as follows:

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

Since, DIRS is searched before APP_DIRS, you're template will be found first.

References:

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

Another possible solution

I notice now that captcha/includes/js_v2_checkbox.html is included by captcha/widget_v2_checkbox.html.

I'm not sure about what happens exactly when widget_v2_checkbox.html is loaded from captcha module ... so I would duplicate the "including" widget_v2_checkbox.html as well into your project's templates folder.

You might also decide to copy the full "templates/captcha" folder contents into you project, for consistency.

Just keep an eye on possibile future changes of those templates when upgrading the captcha module.

Can I see the order of your INSTALLED_APPS? It could be that you are rendering django-recaptcha captcha templates before you render your own templates. To fix this you could move the the external app captcha last in the INSTALLED_APPS list.

Related