article

Friday, June 5, 2020

Django How to Add reCAPTCHA to a Django Site


Django How to Add reCAPTCHA to a Django Site

Google’s reCAPTCHA is a very popular solution to protect your application or website against bots and spam.

In this tutorial I will show how to How to Add reCAPTCHA to a Django Site

First, register your application in the reCAPTCHA admin. https://www.google.com/recaptcha/admin



settings.py
 
#settings.py
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}

GOOGLE_RECAPTCHA_SECRET_KEY = '6LelrwAVAAAAAPDmyx9HFbLaPdvf4ZkhfjLsm_q8'
views.py
 
#views.py
import json
import urllib

from django.shortcuts import render, redirect
from django.conf import settings
from django.contrib import messages

from myapp.models import Comment
from myapp.forms import CommentForm


def comments(request):
    comments_list = Comment.objects.order_by('-created_at')

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():

            recaptcha_response = request.POST.get('g-recaptcha-response')
            url = 'https://www.google.com/recaptcha/api/siteverify'
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': recaptcha_response
            }
            data = urllib.parse.urlencode(values).encode()
            req =  urllib.request.Request(url, data=data)
            response = urllib.request.urlopen(req)
            result = json.loads(response.read().decode())

            if result['success']:
                form.save()
                messages.success(request, 'New comment added with success!')
            else:
                messages.error(request, 'Invalid reCAPTCHA. Please try again.')

            return redirect('comments')
    else:
        form = CommentForm()

    return render(request, 'comments.html', {'comments': comments_list, 'form': form})
models.py
 
#models.py
from django.db import models

class Comment(models.Model):
    text = models.TextField(max_length=1000)
    created_at = models.DateTimeField(auto_now_add=True)

  
    class Meta:  
        db_table = "comments"
forms.py
 
#forms.py
from django import forms

from myapp.models import Comment


class CommentForm(forms.ModelForm):
    text = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}),
        required=True,
        max_length=1000
    )

    class Meta:
        model = Comment
        fields = ('text', )
urls.py
 
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url


urlpatterns = [  
    path('admin/', admin.site.urls),  
    url(r'^comments/$', views.comments, name='comments'), 
]
templates/comments.html
//templates/comments.html
{% extends 'base.html' %}

{% block javascript %}
  <script src='https://www.google.com/recaptcha/api.js'></script>
{% endblock %}

{% block content %}
  <h1 class="page-header">Comments</h1>
  <ul>
    {% for comment in comments %}
      <li><small>({{ comment.created_at }})</small> {{ comment.text }}</li>
    {% endfor %}
  </ul>
  
  {% if messages %}
  <ul class="messages">
    {% for message in messages %}
      <li class="{{ message.tags }}">{{ message }}</li>
    {% endfor %}
  </ul>
{% endif %}
  <hr>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <div class="g-recaptcha" data-sitekey="6LelrwAVAAAAAMKd-jsIvtpFJNkVD0jJF6BhQEJP"></div>
    <button type="submit" class="btn btn-primary">Post</button>
  </form>
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django How to Add reCAPTCHA to a Django Site{% endblock %}</title>
 <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
 
 <div class="container">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django How to Add reCAPTCHA to a Django Site</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %}
  
        {% endblock %}
    </div>
    </div>
{% block javascript %} {% endblock %}

<style>
ul {list-style:none;}
.alert-success, .alert-warning, .alert-info, .alert-danger {
 background-repeat: no-repeat;
 background-position: 10px center;
 height: 40px;
 text-transform: uppercase;
 font-size: 11px;
 line-height: 22px;
 margin-bottom: 20px;
 padding-top: 10px;
 padding-right: 10px;
 padding-bottom: 10px;
 padding-left: 50px;
  
}
.alert-success     {
 background-color: #EBF8D6;
 border: 1px solid #A6DD88;
 color: #539B2D;
 background-image: url({% static 'img/accept00.png' %});
}
.alert-warning      {
 background-color: #FFECE6;
 border: 1px solid #FF936F;
 color: #842100;
 background-image: url({% static 'img/delete00.png' %});
}
.alert-info    {
 background-color: #D3EEF1;
 border: 1px solid #81CDD8;
 color: #369CAB;
 background-image: url({% static 'img/info0000.png' %});
}
.alert-danger   {
 background-color: #FFFBCC;
 border: 1px solid #FFF35E;
 color: #C69E00;
 background-image: url({% static 'img/warning0.png' %});
}
.close-notification     {
 width: 16px;
 height: 16px;
 position: absolute;
 background: url({% static 'img/close000.png' %}) no-repeat;
 top: 4px;
 right: 4px;
 cursor: pointer;
}
</style>
</body>
</html>

Related Post