Showing posts with label DateTIme. Show all posts
Showing posts with label DateTIme. Show all posts

Saturday, October 20, 2007

Django Date Added and Modified

There has been some discussions in the django-developers list about removing auto_now and auto_now_add helpers for the date related fields. Since this functionality is very useful in those discussions some methods has been suggested, but i think that there has been no further advance in this subject.

For a new project I have been working on we are using trunk code and we want to be sure that for the launch date we still have full functionality, so we created 2 custom fields in order to be able to use them directly on the models and have the desired values automatically set. They work for DateTimeFields only, but the idea could be used also for DateFields.

In a file named fields.py we put this:

from django.db import models
import datetime

class AddedDateTimeField(models.DateTimeField):
def get_internal_type(self):
return models.DateTimeField.__name__
def pre_save(self, model_instance, add):
if model_instance.id is None:
return datetime.datetime.now()
else:
return getattr(model_instance, self.attname)


class ModifiedDateTimeField(models.DateTimeField):
def get_internal_type(self):
return models.DateTimeField.__name__
def pre_save(self, model_instance, add):
return datetime.datetime.now()

Then in any models file we can import them and just use! Something like this for example:

class Location(models.Model):
""" Some place's ubication """
name = models.CharField(_('Name'), maxlength=64, blank=False)
date_added = AddedDateTimeField(_('Date added'), editable=False)
date_modified = ModifiedDateTimeField(_('Date modified'), editable=False)
I hope the community finds this useful!