[Fixed]-Django form: setting initial value on DateField

17๐Ÿ‘

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 ๐Ÿ˜‰

๐Ÿ‘คCarlos Parra

5๐Ÿ‘

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

2๐Ÿ‘

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.

๐Ÿ‘คry_a

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'}),
    )

0๐Ÿ‘

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 %}
๐Ÿ‘คopenHBP

Leave a comment