2

I have a CharField that is normally empty. I want to send out an e-mail notification to all managers (using mail_managers) when the field is set to a non-empty value. Changes to this field should only happen via the admin site.

I assumed this might be something I could do via signals but I do not see an appropriate signal listed in the documentation. Any ideas?

Belmin Fernandez
  • 8,307
  • 9
  • 51
  • 75

1 Answers1

6

You will need to add some history to the field if you don't want updates if the field is changed again but just adding a save method to your model similar to should work:

from django.db import models

class Test(models.Model):
    empty_field = models.CharField(max_length=20, blank=True)
    def save(self):
        if self.pk is not None:
            orig = Test.objects.get(pk=self.pk)
            if orig.empty_field != self.empty_field and len(self.empty_field) > 0:
                mail_managers ... 
        super(Test, self).save() # Call the "real" save() method                

See http://www.djangoproject.com/documentation/models/save_delete_hooks/ and Django: When saving, how can you check if a field has changed?

Community
  • 1
  • 1
sunn0
  • 2,918
  • 1
  • 24
  • 25
  • Ahh! The history value would be the key. Gr. Hate when I miss the obvious. Once I make some sort of old_value field, I could just use the signal mechanism. Thanks! – Belmin Fernandez Nov 12 '10 at 02:43
  • Updated the code sorry it is late and was not thinking. You will only need a boolean field to check if the field was ever changed from empty to something IF you want to make sure that no mail is sent if the value is changed back to empty and then changed again :) – sunn0 Nov 12 '10 at 02:45
  • Good thinking sunn0. Appreciate it. – Belmin Fernandez Nov 12 '10 at 03:08