user1187968
user1187968

Reputation: 8036

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'

Upvotes: 15

Views: 24849

Answers (7)

Onyilimba
Onyilimba

Reputation: 1217

For anyone who wants the value to show up in the form UI on the webpage should set the value on the form widget attribute. Eg: forms.DateTimeField(widget=forms.DateInput(attrs={"type":"date", "value": datetime.date.today().strptime("%Y-%m-%d")}))

Upvotes: 0

Aytekin827
Aytekin827

Reputation: 1

just this code worked for my case

set init method!

override Form that you want to change attribute

and set initial value in which need to be changed of set with initial value

def __init__(self, *args, **kwargs):
    super(AssignedModelForm, self).__init__(*args, **kwargs)
    self.initial['finished_date'] = timezone.now()  # Here

Upvotes: -1

One way I've found for this to work regardless of locale is to define a function that returns the date by forcing the expected format.

import datetime
def today_ymd():
    """Return today in format YYYY-MM-DD"""
    return datetime.date.today().strftime('%Y-%m-%d')

Then passing the reference of that function to the initial parameter (function name without parentheses).

class MyForm(forms.Form):
    my_date = forms.DateField(
        initial=today_ymd,
        widget=forms.DateInput(attrs={'type': 'date'}),
    )

Upvotes: 1

ry_a
ry_a

Reputation: 41

Old question but it works when you use a simple datetime object. For example.

tomorrow = datetime.today() + timedelta(days=1)
send_at_date = forms.DateField(
    required=True,
    initial=tomorrow,
    widget=DateInput(attrs={"type": "date"}),
)

Hopefully this helps someone else.

Upvotes: 2

openHBP
openHBP

Reputation: 691

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.

{% block js %}
    {{block.super}}
    <script>
        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 current_date() {
            let now = new Date();
            return date_2_string(now)
        }
        $("#date").val(current_date());
    </script>
{% endblock js %}

Upvotes: 0

Romain Reboulleau
Romain Reboulleau

Reputation: 306

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

Upvotes: 5

Carlos Parra
Carlos Parra

Reputation: 1067

You can set the default value in the same line where you're creating the DateField:

date = forms.DateField(initial=datetime.date.today)

Or if you want to pass a specific date, you could create a funciton and pass it to the DateField, as follows:

def my_date():
    return datetime.date(year=today.year-1, month=today.month, day=today.day)


class MyForm(forms.ModelForm):
    #...
    date = forms.DateField(initial=my_date)
    #...

In addition, you could review the docs for more help on this ;)

Upvotes: 19

Related Questions