New Comment Notification by E-mail

This little trick certainly isn't anything special. Several other folks have posted about how to have Django send out an e-mail automagically when a new comment has been posted on your site. However, a lot of these other posts seem to be pre-Django 1.0. Some groovy changes took place with the signal system slightly before Django 1.0 was released, so I thought I'd share my method of having Django notify me by e-mail when someone posts a comment on my sites.

My code follows:

from django.db.models.signals import post_save
from django.core.mail import mail_admins
from django.contrib.comments.models import Comment

def notify_of_comment(sender, instance, **kwargs):
    message = 'A new comment has been posted.\n'
    message += instance.get_as_text()

    mail_admins('New Comment', message)

post_save.connect(notify_of_comment, sender=Comment)

Nice and simple, right? Right. All this does is it creates a callback function called notify_of_comment and waits for Django to signal that a Comment object has been saved. Any time that signal is intercepted, the callback will send off an e-mail to anyone in the settings.ADMINS list.

You should be able to put such code anywhere in your project so long as that anywhere is loaded when your project starts up. I usually put signal interceptors in an __init__.py file somewhere, though they should work just as well in a models.py or urls.py file.

I realize that the django-comment-utils project is capable of notifying when a comment has been posted, but I didn't want much else from the project. That is why I did it this way ;)

Comments

Comments powered by Disqus