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.
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
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 ;)
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"
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With