问题
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?
回答1:
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?
来源:https://stackoverflow.com/questions/4160889/send-an-e-mail-notification-when-a-django-charfield-is-modified-via-the-admin-si