[Fixed]-Django Form DateInput with widget in update: loosing the initial value

27👍

I managed to make it work. Following the cause of the issue, I hope it can be useful to others.

The HTML <input type='date'> element wants a date in the format YYYY-mm-dd; in fact an example of working HTML must be like this:

<input type="date" name="date" value="2020-03-31" 
class="form-control dateinput form-control" 
placeholder="Select a date" required="" id="id_date">

Since by default the form.DateInput produces the element <input type='text'>, it expects a date in the local format: let’s say ’31/03/2020′.

Forcing the 'type': 'date' and local format format=('%d/%m/%Y') or not passing a format at all, it ignores the value passed since the <input type='date'> wants format=('%Y-%m-%d')

At last the correct instruction was:

widgets = {
    'date': forms.DateInput(
        format=('%Y-%m-%d'),
        attrs={'class': 'form-control', 
               'placeholder': 'Select a date',
               'type': 'date'
              }),
}

0👍

Recently, I coded:

  1. date = models.DateTimeField() in models.py
  2. widgets = {'date': NumberInput(attrs={'type': 'date'})} in forms.py
  3. form = <ModelForm>(instance=<model_instance>, data=request.POST) in views.py

and ran into the same problem. I figured it out by changing to:

widgets = {'date': DateInput(attrs={'type': 'date'})} in forms.py.

Maybe how to pre-fill the form matters in views.py. Another difference is , I imported DateInput from django.forms.widgets, not django.forms.

Leave a comment