There are some old samples available online for doing this, but the 1.0 version of Django is not compatible with those. So I thought I’d share my solution for sending notification mails whenever there’s been posted a new comment on my Django site using Django signals.
The old way of connecting to a signal was:
dispatcher.connect(myFunction, signal=models.signals.post_save, sender=myModel)
The new way is:
models.signals.pre_save.connect(myFunction, sender=myModel)
So when you want to send an email whenever there’s a new comment posted by someone, without changing existing code you will have to do something like this:
from django.contrib.comments.models import Comment
from django.core.mail import send_mail
from django.db.models import signals
def mail_comment(instance, **kwargs):
subject = 'subject of the mail'
msg = 'Comment text:\n\n%s' % instance.comment
send_mail(subject, msg, 'noreply@djangodays', ['email@djangodays.com'])
signals.post_save.connect(mail_comment, sender=Comment)
If you put this code in your __init__.py file it should work fine. Putting this in there is probably not the Django way of doing things, but I’m not sure where to put it instead… I anyone found a better way of doing this, please share it in the comments!
Thanks for this. I’ve been trying to find a good example online all morning. The Django documentation for converting this isn’t exactly straight forward.
I believe, the right place to put this code, is inside your models.py. Because its part of your bussines logic. Dont you agree?
And thanks for this …
I am glad I found this site! Great post!
Nice to hear we could help you out!
Hey! Great Stuff!,
Works a charm boys. The only strange thing is that I receive the mail twice… hrm…