Google recaptcha integration with django applicaton

Recently I have used google recaptcha with my django application for registration process.

There are following steps to integrate with your django application.

  1.  Firstly go to this link - https://developers.google.com/recaptcha/  and click on get started.
  2. Now click on  add  sign up api keys for google recaptcha.
  3. enter label name (e.g.- Myapp) and domain(e.g. - localhost) for your local project
  4. and saved the recaptcha
  5. copy the site key and secret key and added into your settings for example     
  6.  RECAPTCHA_PUBLIC_KEY = '6LdUAAAAAD97sRFALHoKmVWbHxE7kdXAUCed'
    RECAPTCHA_PRIVATE_KEY = '6LUAAAAAARB_-RRMI4ynXAw8mDC8fVUrDud' 
one thing more add RECAPTCHA_VERIFICATION_URL = 'https://www.google.com/recaptcha/api/siteverify'  in settings.py file which are used in your forms.

Then go to your template where you show recaptcha .
and add this code in your template.

<div class="g-recaptcha" data-sitekey="6Ld_EwkUAAAAADmVWbHxE7kdXAUCed"></div> 


next validate your recaptcha through forms

in your forms.py which are used for your registration add this code.


forms.py
 ##############
            recaptcha_response = self.request.POST.get('g-recaptcha-response')
            print(recaptcha_response) 
            if not recaptcha_response:
                raise ValidationError('Oops, it seems you forgot to confirm '
                                      'you\'re not a robot')
             
            payload = {'secret': RECAPTCHA_PRIVATE_KEY,
                       'response': recaptcha_response}
             
            response = requests.post(RECAPTCHA_VERIFICATION_URL, data=payload)
             
            try:
                response = response.json()
            except Exception as e:
                raise ValidationError('Unable to verify captcha from server: %s' % e.__str__())
             
            if not response['success']:
                raise ValidationError('Invalid captcha, please try again...')

 ############


and then add following code in your template:

########
                            {% if form.recaptcha.errors %}
                                {{ form.recaptcha.errors }}
                            {% endif %}
 ##########

Don't forget to add the script file in your template.

<script src='https://www.google.com/recaptcha/api.js'></script>


Thanks

Gurmukh singh





Comments

Post a Comment

Popular posts from this blog

Google Calendar api with django application

Create cronjob for django management command async process