0

Hello i'm working on a blog app and I have a model:

class Post(models.Model):
    title = models.CharField(max_length=255)
    <..>
    is_published = models.BooleanField(default=False)                                  
    time_publish = models.DateTimeField()
    time_edit = models.DateTimeField(auto_now=True)
    time_create = models.DateTimeField(auto_now_add=True)

And i want to set that, when user sets is_published=True and .save() is called then time_publish would save current time.

The problem is that i don't know what route i should take. Overwrite .save() or make something with signals or what? I would appreciate some links to Docs.

Sorry if it's dublicate but i din't knew how the question of such matter should be named.

Update:

So thanks to manji i produced this code that works:

def save(self, *args, **kwargs):
    if self.pk is not None:
        orig = Post.objects.get(pk=self.pk)
        if not orig.time_publish and self.is_published:
            self.time_publish = datetime.now() 
        elif not self.is_published:
            self.time_publish = None
    super(Post, self).save(*args, **kwargs)   
JackLeo
  • 4,579
  • 9
  • 40
  • 66

1 Answers1

1

The simplest solution (and django compliant) is to override your model's save method.

class Post(models.Model):
    ...

    def save(self, *args, **kwargs):
        if self.is_published:
            self.time_publish = datetime.now() # don't forget import datetime
        super(Post, self).save(*args, **kwargs)
        ...

More informations here: Overriding predefined model methods

manji
  • 47,442
  • 5
  • 96
  • 103
  • Or as found out override `clean` method that validates forms. But save would be better place i think – JackLeo Jun 09 '11 at 17:24
  • 1
    @JackLeo you wouldn't want to do that in `clean()` or you may end up with inconsistent data when when models are populated without forms. – Shawn Chin Jun 09 '11 at 17:26
  • but in this case every time i modify object it rewrites publish date. is there any flag `is modified`? – JackLeo Jun 09 '11 at 17:38
  • found it: http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed – JackLeo Jun 09 '11 at 17:41