Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override external app template in Django?

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',
            ],
        },
    },
]
like image 486
konichiwa Avatar asked Oct 15 '25 08:10

konichiwa


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

like image 82
Mario Orlandi Avatar answered Oct 16 '25 21:10

Mario Orlandi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!