Datefield not showing a default value
I tried using a DateField and show a default value, but it does not show on the page (but in the HTML):
class foo(models.Model):
date = models.DateField()
class FooForm(ModelForm):
class Meta:
model = Foo
fields = "__all__"
widgets = {"date": DateInput(format=("%d-%m-%Y"), attrs={"class": "form-control", "value": timezone.now().strftime("%d-%m-%Y"), "type": "date"}),}
this produces:
<input type="date" name="date" value="29-02-2024" class="input" prod_date="input" required="" id="id_date">
which shows as:
But not with the current date as placeholder.
The format of the widget is YYYY-MM-DD, so 2024-02-29 in this case. That being said, don't set the value through the widget attributes: one of the tasks of the form (fields) is converting Python values to the corresponding value in the widget, so essentially you are duplicating boilerplate logic, and as you found out yourself, this conversion is often quite complicated:
from datetime import date
class Foo(models.Model):
date = models.DateField(default=date.today)
class FooForm(ModelForm):
class Meta:
model = Foo
fields = '__all__'
widgets = {
'date': DateInput(
format=('%d-%m-%Y'),
attrs={'class': 'form-control', 'type': 'date'},
),
}
