Overriding Widgets templates not working (following help), template loader not searching app dirs

Hi Ken,

Out of interest (or maybe this will help you one day), got it working as follows (the default django renderer is left untouched, but the project has an additional “Office” style renderer that can be passed into form's renderer argument:


from django.forms.renderers import TemplatesSetting, BaseRenderer
from django.template import engines


class OfficeRenderer(BaseRenderer):
    def get_template(self, template_name):
        # Engine name is a UNIQUE alias in settings.TEMPLATES, if the same backend is used multiple times
        engine = engines['office']
        return engine.get_template(template_name)

    def render(self, template_name, context, request=None):
        """Rendering widgets does not use the context processor, manually add (hackish)"""
        context['gui'] = self.gui
        return super().render(template_name, context)


@functools.lru_cache()
def get_office_renderer():
    """Based on django.forms/renderers.py"""
    renderer = OfficeRenderer()
    return renderer

Context processor:

def add_office_gui(request):
    return { 'gui': 'office' }

With settings.py set to:

import django

# Refer to:  https://docs.djangoproject.com/en/4.0/ref/forms/renderers/#django.forms.renderers.TemplatesSetting
django_form_templates = django.__path__[0] + '/forms/templates'
office_form_templates = Path(CORE_DIR, 'gui/templates_office')   # your own dir here

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [lc_admin_templates, wc_html],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',  # Adds user to context
                'django.contrib.messages.context_processors.messages',
                'core.base.context_processors.linkcube',
                'pwa.context_processors.UnregisterPwaSw',
            ],
            'debug': TEMPLATE_DEBUG,
        },
    },
    {
        'NAME': 'office',
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [office_form_templates, django_form_templates],
        'APP_DIRS': False,
        'OPTIONS': {
            'context_processors': ['core.gui.context_processors.add_office_gui'],
            'debug': TEMPLATE_DEBUG,
        },
    },
}
2 Likes