I am on Django 5.0.7. I wanted to define a custom widget SearchBar, which when associated with a CharField, would automatically render a text input box for search, followed by a search button. I created a template html and put it at a custom location. I tried to create a new widget by inheriting from django.forms.widgets.Input
, but when I give template_name=
, it tries to locate the path in django/forms/templates
only, not my custom location myapp/forms/templates
. It looks like this path is baked into django.template.backends.django.DjangoTemplates
. Is there a simpler way than inheriting from DjangoTemplates then adding template paths to achieve what I want?
BTW, I use Bootstrap5, and so also use django-bootstrap5, so I suppose I need to write a renderer for this too.
Would I be better off manually rendering the field and button in every form by hand rather than define a custom widget?
Here's the code:
class SearchBar(django.forms.widgets.Input):
input_type = 'search'
template_name = 'widgets/search.html'
where the actual template is in myapp/forms/templates/widgets/search.html
. Just for a starter, I copied code from django/forms/templates/django/forms/widgets/text.html
to search.html
. It fails with TemplateNotFound
for widgets/search.html
. If it had worked, I was hoping to add button html to the template.
where the actual template is in
myapp/forms/templates/widgets/search.html
.
That means Django will not find it, you locate this under:
myapp/templates/widgets/search.html
so without the .forms/