Send an e-mail notification when a Django CharField is modified via the admin site

孤者浪人 提交于 2019-12-06 11:52:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!