I want to set the initial date as yesterday in a django form my code is here:
class Bilag(models.Model):
dato = models.DateField()
tekst = models.CharField(max_length=100)
konto = models.CharField(max_length=10)
avd = models.CharField(max_length=10, null=True,blank=True)
avdnavn = models.CharField(max_length=30, null=True,blank=True)
kasseid = models.CharField(max_length=10)
belop = models.FloatField()
def __unicode__(self):
return self.tekst
class BilagForm(ModelForm):
class Meta:
model = Bilag
widgets = {
'dato': SelectDateWidget()
}
initial = {
'dato': yesterday()
}
and the yesterday function:
def yesterday():
yesterday = (datetime.date.today() - datetime.timedelta(1))
return yesterday
But it just displays todays date when i look at the form
You could set the initial value in the ModelField, though it would then be called default
. I assume you only want to do it on the form, in which case you'd need something like:
class BilagForm(forms.ModelForm):
dato = forms.DateField(widget=SelectDateWidget(), initial=yesterday)
class Meta:
model = Bilag
Don't forget that you can't include the parentheses after yesterday
-- just pass the callable, otherwise yesterday()
will be evaluated immediately and not be dynamic (see the bottom of this section).
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