Using Django 4,
Here it explains how to override a widget template:
Each widget has a
template_name
attribute with a value such asinput.html
. Built-in widget templates are stored in thedjango/forms/widgets
path. You can provide a custom template forinput.html
by definingdjango/forms/widgets/input.html
, for example. See Built-in widgets for the name of each widget’s template.
I.e.:
Step 1. Place folder in correct namespaced dir
And here explains how to perform the next steps:
'django.forms'
inINSTALLED_APPS
and at least one engine withAPP_DIRS=True
.
I.e.
Step 2. Add django.forms
to installed apps
Step 3. Set FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
in settings.py
With regards to the above steps:
- I placed the overriding template in:
<myapp>/templates/django/forms/widgets/input.html
myapp
appears beforedjango.forms
inINSTALLED_APPS
- Here is a snippet from settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [my_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',
],
'debug': TEMPLATE_DEBUG,
},
},
]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
However after performing the above it does not pick up the overriding template (which has a very obvious change init).
In django/template/loaders/filesystem.py
in the method def get_template_sources
(line 28), if I print the result of for self.get_dirs():
it prints:
/home/michael/.venv/project/lib/python3.8/site-packages/django/forms/templates
/home/michael/.venv/project/lib/python3.8/site-packages/django/forms/templates
So I can see for sure the app dirs are not being added. I keep checking my paths but they seem correct, don’t know what else to try.
PS, If I try adding a second entry to TEMPLATES
in settings.py
, e.g.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [my_admin_templates, wc_html],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [],
'debug': TEMPLATE_DEBUG,
},
},
{
'BACKEND': 'django.forms.renderers.TemplatesSetting',
'APP_DIRS': True,
'OPTIONS': {
},
},
]
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
Then it fails with:
File "/home/michael/.venv/project/lib/python3.8/site-packages/django/template/utils.py", line 81, in __getitem__
engine = engine_cls(params)
TypeError: TemplatesSetting() takes no arguments