• 13. Mär
  • 13:48
  • 2010

  • Updated
  • 16. Mai
  • 13:40
  • 2010

Comment Spam Protection

Update: Ironically this blogpost gets the most spamments. Therefore comments are now closed.

Recently I got really fed up by how much spam I receive in the form of comments. I decided that a captcha is not an ideal solution, since I just hate them and clever spambots have nice OCR. A common pattern I found inside these "spamments", as I call them, is that they write HTML code inside the textfield, specifically a lowercase A tag. Solution: moderate a comment if we find "a href" inside it.

Thanks to django's very flexible comments framework, it's a breeze to actually do all kind of weird stuff with comments.

class EntryModerator(CommentModerator):
    ....
    def moderate(self, comment, content_object, request):
        if self.auto_moderate_field and self.moderate_after:
            if self._get_delta(datetime.datetime.now(), getattr(content_object, self.auto_moderate_field)).days >= self.moderate_after:
                return True
            if 'a href' in comment.comment:
                return True
       return False

There you go. This is a pretty basic protection (it only checks for lowercase "a href"), but right now I'm confident with it, I (yet) don't get that many comments. Note that you have access to the comment itself and the request object. This allows very advanced checks for IPs etc - or you simply tie in Akismet (which also has python bindings) at this point.

Anyway, there are cases where users enter links by using html markup. So wouldn't it be nice to let the user know that his comment has been moderated and why?
This is actually dead simple, since we have full access to the comment object inside the "posted.html" template. Mine looks like this:

{% if comment.is_public %}
    <h1>{% trans "Thank you for your comment" %}.</h1><br />
    <a href="{{ comment.get_absolute_url }}">View it!</a>
{% else %}
    <h1>Your comment has been moderated because of denied usage of HTML</h1><br />
    It must be reviewed and approved by the admin.
{% endif %}

It's always nice to let the user, or rather say spambot, know what went wrong.

By the way, did you actually know that you can have a look at the blog engine behind originell?

blog comments powered by Disqus

This is Luis’ blog. Here he posts about stuff that he encounters in everday life, both virtual and real.

Recently he wrote “Complete Facebook Profile?”, “Lighttpd's X-Sendfile”, “Modular Lighttpd Configurations”, “Fool Facebook's Like-Button” and “Calculating Battery Health”.

Contact