Content tagged with "comments"

Automatic moderation with Django 1.0 Comments Post on Oct 16, 2008

This one was actually a lot easier than I thought it would be. The Django comments framework was totally revamped for the Django 1.0 release, and it is now way mo betta :)

But! Even with all the new anti-spam stuff built in, I needed all comments to go into a moderation queue for a client site. At first I tried the pre_save hook to change the is_public flag on the comment, but there's no way (that I could tell) how to distinguish when the comment was submitted, and when it was moderated.

The solution

The Django folks are always thinking :) Then put in a sweet little hook called comment_will_be_posted that gets called when the user submits the comment. Hook in and change the 'is_public' flag to 'False', and the comments automatically go into the moderation queue.

The Code

from django.contrib.comments.models import Comment
from django.core.mail import send_mail
from django.contrib.sites.models import Site
from django.contrib.comments.signals import comment_will_be_posted
from django.conf import settings

def comment_set_public(sender, comment, request, **kwargs):
    # set the flag to false so it hits moderation
    comment.is_public = False
    
    # send an email
    subject = '%s > New Comment on %s' % (Site.objects.get_current(), comment.content_object.title)
    msg = """
You have a new comment on the item:\n%s\n\n
Comment text:\n%s\n\n
To moderate comments, visit the link below:\n
http://%s/comments/moderate/
          """ % (comment.content_object.title, comment.comment, Site.objects.get_current())
    send_mail(subject, msg, settings.COMMENT_FROM_EMAIL, [settings.COMMENT_TO_EMAIL])
    
    # from the docs: "If any receiver returns False the comment will be discarded..."
    # so there's much more potential for spam checking/protection
    return True

# the hook
comment_will_be_posted.connect(comment_set_public, sender=Comment)

Other goodies

Just for good measure, we put email notification in the same place which is handy (otherwise, how would you know comments were added?). The other super handy goodie with Comments 1.0 is they have added views for moderation also. Just point your browser to:

http://mysite.com/comments/moderate/

and you get a nice little view that looks just like the admin interface with which to moderate your comments. Obviously, if you're not logged in, it will prompt you to do so :)

Cheers, Af

PS: Here's a little screen to give you a taste: Django 1.0 Comments Moderation Screen