How to automatically update the date field through Django Class model

How to automatically update the date field through Django Class model::

 

For the update of table field automatically from the django model we need to use

the auto_now=False and auto_now_add=False field options

date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)

From Django ::

DateField

class DateField([auto_now=Falseauto_now_add=False**options])

A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:

DateF
ield.auto_now
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override.

The default form widget for this field is a TextInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key.

Example::

from django.db import models

class Task(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

sources:
https://docs.djangoproject.com/en/1.7/ref/models/fields/#datefield

https://timonweb.com/tutorials/automatic-created-and-updated-datetime-fields-for-django-models/

 

Leave a Comment