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 ).
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())
I've tried all proposed solutions, none of them are working. The only thing that works for me is to set the date using JavaScript (J Query)
{% block js %}
{{block.super}}
<script>
Date.prototype.addDays = function (days) {
let date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function date_2_string(dt) {
let day = ("0" + dt.getDate()).slice(-2);
let month = ("0" + (dt.getMonth() + 1)).slice(-2);
let today = dt.getFullYear()+"-"+(month)+"-"+(day);
return today
}
function get_date(dd=0) {
let now = new Date();
return date_2_string(now.addDays(dd))
}
$("#dato").val(get_date(-1));
</script>
{% endblock js %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.