Overriding Field Widgets In Django Doesn't Work. Template Not Found. The Solution

04 May · by Tim Kamanin · 1 min read

One day you may want to override a default Django form input widget. Let's say; you'll want to tweak a Date widget, so it has type="date" on it.

So you'd go out and do the regular drill:

1) Find the source file inside the Django dir: forms/templates/django/forms/widgets/input.html;

2) Copy and save its contents into your project's main templates directory as templates/django/forms/widgets/date.html;

3) Tweak the source and make it look like:

<input type="date" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %} />

4) Restart the server and expect all Date fields now be natively supported by Chrome browser.

But in the end, it won't work.

You can keep hitting the refresh button as many times as you want but it won't work until you do the following steps:

1) Add 'django.forms' to your INSTALLED_APPS;

2) Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to your settings.py.

Why is that? Well it's a little low-level Django quirk you can read about in the docs here: https://docs.djangoproject.com/en/2.0/ref/forms/renderers/#django.forms.renderers.TemplatesSetting

Which means, if you want to override default widget templates, you need to explicitly register 'django.forms' as an app and specify your FORM_RENDERER as 'django.forms.renderers.TemplatesSetting'.

I hope this saves you some time, my friend.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials

Comments