Django datefield in a model form is generated in html with type=text rather than type=date

109 Views Asked by At

here is my forms.py:

from django import forms
from django.forms import DateTimeInput, DateInput
from property.models import PropertyView

class DetailForm(forms.ModelForm):
    class Meta:
        model = PropertyView
        
        datepurchased = forms.DateField(input_formats=['%d/%m/%Y'])
        fields = ['address1', 'address2','postcode','datepurchased']

and here is how the form appears: form with text instead of date input

2

There are 2 best solutions below

0
willeM_ Van Onsem On

You can make a custom widget:

from django.forms.widgets import DateInput


class MyDateInput(DateInput):
    input_type = 'date'

and then plug in this custom widget

class DetailForm(forms.ModelForm):
    datepurchased = forms.DateField(
        input_formats=['%d/%m/%Y'], widget=MyDateInput
    )

    class Meta:
        model = PropertyView
        fields = ['address1', 'address2', 'postcode', 'datepurchased']
2
Richard Smith On

I seem to have found the solution for this. If I include a widget in the form as follows:

widgets = {'datepurchased': DateInput(attrs={'type': 'date'})} 

This has the effect of enforcing the input type to 'date'. However, I am still wondering why this is necessary. Surely the fact that it is a date field should be enough for django to give it the right input type? Any thoughts?