Search code examples
djangodjango-comments

django: Adding simple captcha to django comments


I am trying to understand how it's possible to use http://code.google.com/p/django-simple-captcha/ with django comments. I have done all as described here: http://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/

So my forms in custom comment app looks like this:

from django import forms
from django.contrib.comments.forms import CommentForm
from captcha.fields import CaptchaField


class CommentFormWithCaptcha(CommentForm):
    captcha = CaptchaField()

    def get_comment_model(self):
        # Use our custom comment model instead of the built-in one.
        return Comment

And my __init__.py file:

from protected_comments.forms import CommentFormWithCaptcha

def get_form():
    return  CommentFormWithCaptcha

The captcha field is rendered, but I don't understand how to check if input was valid. E.g. simple-captcha docs said following

if form.is_valid():
            human = True

But I don't really understand where I can add this. Is there a method in forms.py I can override?


Solution

  • I'm going to assume that you correctly added your protected_comments app to your settings.py file as specified in the documentation:

    INSTALLED_APPS = [
        ...
        'protected_comments',
        ...
    ]
    
    COMMENTS_APP = 'protected_comments'
    

    Now then, when you render your comment form it's going to place a default URL telling the form where it's going to POST to. You can see the contrib.comments default URLconf here.

    That default view to handle the posted comment already goes through your fields, custom or not, and ensures that they're valid. You'd only have to add:

    if form.is_valid():
        human = True
    

    if this were a custom app that you were adding the captcha to, that didn't already have view functions written for you like contrib.comments does.

    So you're fine, the captcha will validate itself with what you have written already. I just tested it on a demo project to confirm.