6

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

Kracobsen
  • 159
  • 2
  • 11

2 Answers2

7

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

DrMeers
  • 3,959
  • 1
  • 35
  • 36
  • How would I do that for any day, say 23 days before where there is no convenience function like `yesterday()`? `datetime.date.today - datetime.timedelta(days=23)` throws an error. – CGFoX Oct 28 '20 at 19:44
  • Ah ok, found it: https://stackoverflow.com/a/36881345/2745116 – CGFoX Oct 28 '20 at 19:45
0

I think you define initial in the wrong place (class Meta).

From my understanding it should be set as an parameter of the field you're trying to set the initial value for.

Check the docs: http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.Field.initial

Another option would be to use the field's default parameter in your model definition. See this thread for some inspiration: Django datetime issues (default=datetime.now())

Community
  • 1
  • 1
arie
  • 18,135
  • 5
  • 68
  • 76