Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form: setting initial value on DateField

I have the following code to set the initial value for a DateField and CharField. CharField's initial value got set properly, but the DateField's initial value is still blank.

class MyForm(forms.ModelForm):
    dummy = fiscal_year_end = forms.CharField()
    date = forms.DateField()

    def __init__(self, *args, **kwargs):

        super(MyForm, self).__init__(*args, **kwargs)
        today = datetime.date.today()
        new_date = datetime.date(year=today.year-1, month=today.month, day=today.day)
        self.fields["date"].initial = new_date
        self.fields["dummy"].initial = 'abc'
like image 511
user1187968 Avatar asked Apr 27 '16 05:04

user1187968


1 Answers

I'm not sure this is answering the (not 100% clear) initial question, but I got here so here's my solution.

The HTML value attribute of the date field contained the date, but formatted in a way that depended on the language, and was never the expected one. Forcing the date to ISO format did the trick:

class MyForm(forms.ModelForm):
    my_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}))

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.initial['my_date'] = self.instance.my_date.isoformat()  # Here
like image 150
Romain Reboulleau Avatar answered Oct 22 '22 11:10

Romain Reboulleau