Setting yesterday as a start date in a Django form

I want to set the start date as yesterday in the django form, where is my code:

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 yesterday's function:

def yesterday():
    yesterday = (datetime.date.today() - datetime.timedelta(1))
    return yesterday

But it just displays the date when I look at the form

+5
source share
2 answers

You can set the initial value in ModelField, but then it will be called default. I assume that you only want to do this in the form, in which case you will need something like:

class BilagForm(forms.ModelForm):
    dato = forms.DateField(widget=SelectDateWidget(), initial=yesterday)
    class Meta:
        model = Bilag

Remember that you cannot include parentheses after yesterday- just pass the called, otherwise it yesterday()will be evaluated immediately and not be dynamic (see the bottom of this section ).

+6

All Articles