Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value format on Django DateField

Tags:

python

django

I'm trying to specify a default date in a Django model, for example:

from datetime import date

class A(models.Model):
    date = models.DateField(default=date.today())

This works and I can see the default date in a ModelForm, but when I change the form input_format to %d-%m-%Y, the default date never appears in the field.

I've also tried:

from datetime import date

class A(models.Model):
    date = models.DateField(default=date.today().strftime('%d-%m-%Y'))

This doesn't work either. Can anyone help me?


2 Answers

There are two problems here:

  1. the DateField(default=today.today()) will not work, since then the function will be evaluated eagerly, and then the default value is thus the result of that function call. As a result the default value is not calculated when constructing a new object, and hence eventually will be different; and
  2. the representation of a DateField. Now the model layer does not specify a representation, it only specifies how to store values in the database, and defines functions on a model.

We can solve the first problem by passing a reference to the today function, like:

from datetime import date

class A(models.Model):
    date = models.DateField(default=date.today)    # no ()

As for the representation, you should specify the format in the template, for example with the date template filter [Django-doc], like:

<!--  template.html -->
{{ some_a.date|date:'d-m-Y' }}

Or in a form with:

# app/forms.py

class AForm(ModelForm):
    date = DateField(input_formats=['%d-%m-%Y'])
    class Meta:
       model = A
like image 86
Willem Van Onsem Avatar answered May 30 '26 05:05

Willem Van Onsem


You can use the DATE_INPUT_FORMATS setting in your Django project settings, this will allow you to make date.today().strftime('%d-%m-%Y') be accepted by your model field; however, the DateField is stored in your database as the native column of the same type and not as a string with a specific format. There is a difference between storing the data and representing it in your forms, templates or DRF serializers. I really recommend keeping the default format for the database and present the data in the format you want by using the DATE_FORMAT setting to d-m-Y that will take care of presenting your dates in that format as long as the USE_L10N setting is False.

like image 31
codeadict Avatar answered May 30 '26 03:05

codeadict