Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 208
pablete Avatar asked Oct 26 '12 20:10

pablete


3 Answers

Using django-html5

  1. Install django-html5: pip install django-html5

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

  3. 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 ;)

like image 121
jpic Avatar answered Oct 01 '22 19:10

jpic


Here is a simple one:

put this code in anywhere of the form.py

forms.DateInput.input_type="date"
forms.DateTimeInput.input_type="datetime-local" 
like image 21
yjmade Avatar answered Oct 01 '22 19:10

yjmade


here's a code snippet of basically jpic's solution and what I used after looking for the answer here too -->

class EmailTextInput(django.forms.widgets.TextInput):
    """Subclass TextInput since there's no direct way to override its type attribute"""
    input_type ='email'

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'thedate': EmailTextInput()
        }
like image 40
David Lam Avatar answered Oct 01 '22 20:10

David Lam