Django widget override template
Django version < 1.11:
The widget must implement the render
method in order to render a different template:
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string
class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple):
template_name = 'project/widgets/filter.html'
def render(self, data):
...
Do stuff with data
...
return mark_safe(render_to_string(self.template_name))
Django version 1.11:
In the renderer's documentation, we can find the following:
New in Django 1.11:
In older versions, widgets are rendered using Python. All APIs described in this document are new.
And by having a look at the widget source code and specifically on how the Input
widget extends the Widget
class, we can see that you would only need to customize your widget as follows:
class MultiChoiceFilterWidget(forms.widgets.CheckboxSelectMultiple):
template_name = 'project/widgets/filter.html'
Which is what you have already.
You will have to do the below steps to render your new widget template:
1) Add 'django.forms' to your INSTALLED_APPS;
2) Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to your settings.py.
More details : https://docs.djangoproject.com/en/2.0/ref/forms/renderers/#django.forms.renderers.TemplatesSetting