Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting yesterday as initial date in a Django Form

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

like image 972
Kracobsen Avatar asked Mar 30 '11 08:03

Kracobsen


1 Answers

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).

like image 56
DrMeers Avatar answered Oct 20 '22 06:10

DrMeers