Override Django 4 template form widgets

1st: 19 January 2023 • Last Updated: 19 January 2023 • 2 min read

I’ve been wondering how could I get rid of Crispy Forms. I like the idea of the plugin but I do not like the implementation.

CF is based on Django’s Form class code. I mean, you have to write Python code to make it work as it should. I like my Python code not messing with my HTML except, of course, rendering it.

Since Django 4 and it’s HTML Form templates (here), I was wondering if I could start my journey of making CF a thing of the past.

First things first: I should be able to override forms and its widgets. Digging a little bit, I could manage to do that. In fact, it’s quite simple:

  1. You have to import django.forms in your INSTALLED_APPS on the settings.py file:
...
'django.contrib.messages',
'django.contrib.staticfiles',
'django.forms',
...
  1. You have to include the django.forms.renderers.TemplatesSetting as your form renderer, also on you settings.py file:
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
  1. Last, you can override the templates. I decided to have all form related templates under my app structure. To do so, I copied the whole content of the Django instalation under my main templates folder (the on the root of my project). Since my Django instalation is under my .venv folder, all I had to do was (I’m on macOS so, you’ll have to adapt the commands below to your OS):
> mkdir -p templates/django/forms
> cp -R .venv/lib/python3.11/site-packages/django/forms/templates/django/forms/* templates/django/forms/

There you have it! If you try and mess around with the form and widgets templates, you’ll see that your changes will be reflected on how the forms are rendered.

My journey first step is completed!