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
1 2 3 4 5 6 7 8 9 10 11 | #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' |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #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' ) 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}) |
1 2 3 4 5 6 7 8 9 10 | #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" |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #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' , ) |
1 2 3 4 5 6 7 8 9 10 11 | #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' ), ] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //templates/comments.html {% extends 'base.html' %} {% block javascript %} {% 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 %} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | //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> |