[Django]-Why DateTimeField with auto_now_add can not get in form fields

6๐Ÿ‘

โœ…

If you specify auto_now=True, or auto_now_add=True, then you make the field editable=False at the same time. Hence it means it will not show up in the form.

Probably a minimal change would be to specify a default value by using a function, instead of using the auto_now_add=True property, like:

from django.utils import timezone as tz

class TestRule(models.Model):
    code = models.CharField(_('Code'), max_length=56, null=False,
                        blank=False, db_column='code')
    name = models.CharField(_('Name'), max_length=128, null=False,
                        db_index=True, db_column='name', blank=False)
    created_at = models.DateTimeField(_('Created At'), null=False,
                                      db_column='created_at', blank=False,
                                      default=tz.now)

Note that we do not call the now(..) function. If we would do that, then we would set the created_at column to the timestamp when we constructed the models (not the instances of the model). By passing a reference to the now(..) function, the function will be called when a new model instance is added.

Leave a comment