How can I override the 'type' attribute of a ModelForm in Django?

django, django-widget, html, python

Solution

Using django-html5

Install django-html5: `pip install django-html5`

In forms.py, `import html5.forms.widgets as html5_widgets`

Set `widgets['thedate'] = html5_widgets.DateInput`

I did not personally test it because I just found out the trick but thanks to you I'm probably going to use it :D

Just override input_type

You can also make your own widget, here's the idea:

from django import forms

class Html5DateInput(forms.DateInput):
    input_type = 'date'

Refer to `django/forms/widgets.py` for details ;)

Problem

Specifically, I would like to render date widget in a form but I would like it to 'be' HTML5 (so I can just forget about the javascript or whatever and trust Chrome, Opera and Safari to display the datepicker). No javascript solutions please, I have already found those on the web. Here is a snippet of my code, but it still puts the type attribute of the forms field thedate as a "text". ``` #models.py class MyModel(models.Model): user = models.ForeignKey(User) thedate = models.DateField() #forms.py class MyModelForm(ModelForm): class Meta: model = MyModel widgets = { 'thedate': TextInput(attrs={'type': 'date'}), } ``` Can anyone please shed a light? Thanks in advance.

Original source