Django 1.0 mail notification of new comments


Django 1.0 mail notification of new comments

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', [''])

signals.post_save.connect(mail_comment, sender=Comment)

If you put this code in your 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!


6 comments for “Django 1.0 mail notification of new comments”

  1. 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.

    Posted by michael szul | October 11, 2008, 8:19 pm
  2. I believe, the right place to put this code, is inside your Because its part of your bussines logic. Dont you agree?

    And thanks for this …

    Posted by Carlos Leite | October 17, 2008, 4:04 am
  3. I am glad I found this site! Great post!

    Posted by Paul | October 23, 2008, 3:42 pm
  4. Nice to hear we could help you out!

    Posted by Joost | October 23, 2008, 3:45 pm
  5. Hey! Great Stuff!,

    Posted by Pvfnhihc | November 3, 2008, 5:29 am
  6. Works a charm boys. The only strange thing is that I receive the mail twice… hrm…

    Posted by Dave | November 17, 2008, 9:11 pm

Post a comment


  • No categories

Django Hosting:

DjangoDays recommends the following Django hosting provider: