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 ๐
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
- What could cause a Django error when debug=False that isn't there when debug=True
- How to display a user's get_full_name() instead of the username in a Django model form?
- How to construct django Q object matching none
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.
- Generating single access token with Django OAuth2 Toolkit
- Why isn't my Django User Model's Password Hashed?
- ALLOWED_HOSTS and Django
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'}),
)
- Nested field serializer โ Data missing
- Active Django settings file from Celery worker
- Django manage.py settings default
- Django render_to_string() ignores {% csrf_token %}
- Is it correct to modify old migration files in Django?
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 %}
- Differences between `class` and `def`
- Django subquery and annotations with OuterRef
- Django, loop over all form errors
- How do I get a "debug" variable in my Django template context?
- In Django, How do I get escaped html in HttpResponse?