Automatic creation date for Django model form objects?

PythonDjangoDjango Models

Python Problem Overview


What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?

models.py:

created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)

views.py:

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        return HttpResponseRedirect('obj_list')

I get the error:

objects_object.created_at may not be NULL

Do I have to manually set this value myself? I thought that was the point of the parameters passed to DateTimeField (or are they just defaults, and since I've set editable=False they don't get displayed on the form, hence don't get submitted in the request, and therefore don't get put into the form?).

What's the best way of doing this? An __init__ method?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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)

Solution 3 - Python

It is impossible to add the field 'create_at' with 'auto_now_add=True' to local without providing a default. This is because the database needs something to popula te existing rows

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRogerView Question on Stackoverflow
Solution 1 - PythonManoj GovindanView Answer on Stackoverflow
Solution 2 - PythonChitrank DixitView Answer on Stackoverflow
Solution 3 - PythonSamir JemaaView Answer on Stackoverflow