views:

299

answers:

2

I want to send an email when a specific field is changed in a model. Is it possible? Here is what I am looking for. I have a profile model that includes a BooleanField that when the administrator selects to be true I want to send user an email. I know I could put it in a "def save(self):" but, that fires off an email anytime the model is changed and the field is true. Is there a way to have it only email if the field was changed from False to True?

+2  A: 

save method is a perfectly good place for what you want to do:

def save(self):
    if(self.id):
        old_foo = Foo.objects.get(pk=self.id)
        if(old_foo.YourBooleanField == False and self.YourBooleanField == True):
            send_email()
    super(Foo, self).save()
I might change the if statement to this:if not old.field == self.field:
ShawnMilo
He wants to send email only when the value changed from False to True. So checking that values are not equal is not enough.
Was looking for a way to trigger any action when a model is changed ... looks like this is it. Thanks.
Matt Miller
A: 

Use hook a function with your models post_save using django signals (http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save)

In that function use standard django mailing: http://docs.djangoproject.com/en/dev/topics/email/

sharjeel
You will not have the old value in post_save, so there wouldn't be any way of knowing if the value has actually changed or not.