Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic creation date for Django model form objects?

People also ask

Does Django auto generate ID?

Django will create or use an autoincrement column named id by default, which is the same as your legacy column.

How can get current date in Django model?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.

How do I change the default date in Django?

To set Python Django DateField default options, we can set the default argument. to create the date field in our model class. We wrap 'Date' with parentheses to set the default date at the time the class is first defined. Then we set the default argument to datetime.


You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)