Code Koala

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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

  1. Thanks for posting this, comment notifications are about 2 items down on my todo list, so this has been very helpful.
    Posted by: Sam McDonald , 30 nov 2008, 10:37 a.m.
  2. Glad to help!!
    Posted by: wheaties , 30 nov 2008, 10:39 a.m.
  3. You may like to know that in kwargs there's a "created" argument that is set to True if the saved item was Inserted into the DB (aka: Is new).

    You may check it to make sure you do not notify a comment if you edit it
    Posted by: Marc Fargas , 1 dec 2008, 3:08 a.m.
  4. Yup. The version I'm using actually takes that into account, but for the sake of simplicity I didn't include it in this snippet. I still want to know when comments are updated, so I change some of the wording in the message I get.
    Posted by: wheaties , 1 dec 2008, 6:20 a.m.

Post a Comment

:  
:  
:  
:  
:  
:
 

Copyright © 2009 Josh VanderLinden. All rights reserved.
Home : My Ramblings : Projects : About Code Koala : Terms of Use
Design inspired by Free CSS Templates

A Django site.
Powered by Django 1.1 pre-alpha SVN-9699 and Python 2.5.1
1 of 2 active users is reading this page