Category Archives: django forms

Creating HTML5 forms elements in Django forms


Django does have excellent features, however recently I stumbled on implementing a form with HTML5 elements using Django Forms library. Django has IntegerField, FloatField, DateTimeField and DateField etc. classes to provide a validation on the values to be accepted by the application, however they all are rendered as <input type=”text”> in the HTML by default.

By default all these fields take TextInput as their widget, so all I needed was to write custom widgets to get HTML5 elements. Some very simple widgets for email and date types can be as follows:

The widget for email field:

To replace input type from “text” to “email” or “date” we need to create our own class inheriting the Input class (which is also the parent class of TextInput).

The Input class looks as following:

And then in Django forms we add our widget to the field:

and it works!