Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin - Allow manual editing of auto DateTime fields

Is it possible to allow manual editing of auto DateTimeField's on the add / change page of a model. The fields are defined as:

post_date = models.DateTimeField(auto_now_add=True)
post_updated = models.DateTimeField(auto_now=True)

I'm not sure how manually overriding these would exactly work, is the auto updating handled at the database level or in django itself?

like image 425
Runcible Avatar asked Apr 21 '12 16:04

Runcible


2 Answers

auto_now_add=True and auto_now=True assume editable=False. So if you need to correct this field, don't use them.

Auto updating handles at django level. For example, if you update queryset, e.g.

Article.object.filter(pk=10).update(active=True)

won't update post_updated field. But

article = Article.object.get(pk=10)
article.active = True
atricle.save()

will do

like image 128
San4ez Avatar answered Sep 23 '22 15:09

San4ez


auto_now_add=True and auto_now=True assume editable=False. So if you need to modify this field in the admin or in any other ModelForm, then don't use the auto_now_*=True settings.

Automatic updating of these auto_now_* fields is handled at the Django level.

If you update an instance of a model with an auto_now_*=True field, then Django will automatically update the field, e.g.,

class Article(models.Model):
    active = models.BooleanField()
    updated = models.DateTimeField(auto_now=True)
article = Article.object.get(pk=10)
article.active = True
article.save()
# ASSERT: article.updated has been automatically updated with the current date and time

If you want to override this automatic behavior in Django, you can do so by updating the instance via queryset.update(), e.g.,

Article.object.filter(pk=10).update(active=True)
# ASSERT: Article.object.get(pk=10).updated is unchanged

import datetime
Article.object.filter(pk=10).update(updated=datetime.datetime(year=2014, month=3, day=21))
# ASSERT: article.updated == March 21, 2014
like image 35
Rob Bednark Avatar answered Sep 25 '22 15:09

Rob Bednark