Home Plugins Contact Us Demo Sign In Sign Up Free
Django

DJANGO CAPTCHA

1. Create directory 'templatetags' with file keycaptcha.py in it.
File keycaptcha.py content:
from django import template
from settings import KeyCAPTCHA_PrivateKey, KeyCAPTCHA_UserID
from hashlib import md5
from urllib import urlopen
register = template.Library()


@register.inclusion_tag('keycaptcha.html', takes_context = True)
def show_keycaptcha( context, pars="postbut|capcode" ) :
  request = context['request']
  st = pars.split( '|' )
  session_id = request.session.session_key
  ra = request.META['REMOTE_ADDR']
  s1 = md5( session_id + ra + KeyCAPTCHA_PrivateKey ).hexdigest()
  s2 = md5( session_id + KeyCAPTCHA_PrivateKey ).hexdigest()
  return { 
    'kc_button_id':st[0],
    'kc_input_id':st[1],
    'kc_user_id':KeyCAPTCHA_UserID, 
    'kc_s1':s1, 
    'kc_s2':s2, 
    'kc_session_id':session_id }
show_keycaptcha.is_safe = True


def validate_keycaptcha( capcode ) :  
  cap = capcode.split('|')
  if len( cap ) < 3 : return False
  valid_cap_sign = md5( 'accept' + cap[1] + KeyCAPTCHA_PrivateKey + cap[2] ).hexdigest()
  if valid_cap_sign <> cap[0] : return False
  if cap[2].find( 'http://' ) == 0 : 
    try :
      f = urlopen( cap[2] + cap[1] )
      st = f.read()
      f.close()
    except :
      return False
    if st <>'1' : return False
  else : return False
  return True

2. Create keycaptcha template in your templates dir.
keycaptcha.html content:
<!-- KeyCAPTCHA code (www.keycaptcha.com)-->
<input id="capcode" type="hidden" name="capcode" value="123" />
<script language="JavaScript">
    var s_s_c_user_id = '{{kc_user_id}}';
    var s_s_c_session_id = '{{kc_session_id}}';
    var s_s_c_captcha_field_id = '{{kc_input_id}}';
    var s_s_c_submit_button_id = '{{kc_button_id}}';
    var s_s_c_web_server_sign = '{{kc_s1}}';
    var s_s_c_web_server_sign2 = '{{kc_s2}}';
</script>
<script language=JavaScript src="https://backs.keycaptcha.com/swfs/cap.js"></script>
<!-- end of KeyCAPTCHA code-->
3. Edit file settings.py:
...
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
   
   
  # Replace PUT_YOUR_PRIVATE_KEY_HERE and PUT_YOUR_KEYCAPTCHA_USER_ID_HERE
  # with proper values from your keycaptcha.com accont
   KeyCAPTCHA_PrivateKey = PUT_YOUR_PRIVATE_KEY_HERE
   KeyCAPTCHA_UserID =  PUT_YOUR_USER_ID_HERE

   TEMPLATE_CONTEXT_PROCESSORS += (
    "django.core.context_processors.request",
   )
...
4. Add 'capcode' field to your form:
capcode = forms.CharField( label= 'captcha', 
    max_length=1000,
    required=True,
    widget=forms.TextInput(attrs={'type':'hidden'}) 
    )
and clear function for it:
def clean_capcode(self):
    from templatetags.keycaptcha import validate_keycaptcha
    capcode = self.cleaned_data['capcode']
    if not validate_keycaptcha( capcode ) :
        raise forms.ValidationError( "The solution of task you submitted was incorrect." )
        return ''

5. Add {% load keycaptcha %} to your form template and use {% show_keycaptcha %} tag to show captcha
6. Add id="postbut" to your submit button.