The code below also renames the fields more suitably. You can use a similar trick to create other non-editable field types, and also to change other instantiation defaults.
class ModificationDateTimeField(models.DateTimeField):
def __init__(self, editable=False, *args, **kw):
models.DateTimeField.__init__(self, editable=editable, *args, **kw)
def pre_save(self, instance, add):
val = datetime.datetime.now()
setattr(instance, self.attname, val)
return val
class CreationDateTimeField(ModificationDateTimeField):
def __init__(self, editable=False, *args, **kw):
models.DateTimeField.__init__(self, editable=editable, *args, **kw)
def pre_save(self, instance, add):
if not add:
return getattr(instance, self.attname)
return ModificationDateTimeField.pre_save(self, instance, add)
2 comments:
Ah, very nice. I've been trying to solve this problem right now. Thanks for the post!
@grzywacz: of course if you are just creating models containing the standard Field types all you need to do is add editable=False to the creator calls.
I've had problems thinking of a use case for editable=True for these fields, however, since any value input by a user would be overridden by the pre_save() method.
Post a Comment