DEV Community

Cover image for Django - reCaptcha
Yash Patel
Yash Patel

Posted on

Django - reCaptcha

Hello everyone..!

To get started with django-recaptcha, you first need to create a Django project and a Django app. But if you have already created them, you are ready to go.

If you are new to Django and don't know how to create a Django project, then you can read my blog post on "What is Django?".

If you are clear with the above instructions, then let's get started!

Installing reCaptcha

  • Install django-recaptcha you can find link here click me.
  • Install the package using command: pip install django-recaptcha.

Note: Just for your information, the project name and app name might be different for you than mine. In the instructions, I used "Django project" and "Django app" as placeholders. When creating your own project and app, you can name them whatever you like.

Configuring reCaptcha in django settings

  • Open settings.py file and in INSTALLED_APPS list and write 'captcha'.

    INSTALLED_APPS = [
    ...,
    'captcha',
    ...
    ]
    
  • Now add reCaptcha public and private key settings.py.

    RECAPTCHA_PUBLIC_KEY = 'MyRecaptchaKey123'
    RECAPTCHA_PRIVATE_KEY = 'MyRecaptchaPrivateKey456'
    

reCaptcha configuration on Google Cloud

  • Go to: reCaptcha (google.com)

  • Click on v3 Admin Console (You need to login with google account)

  • In label section you can right any label name.

reCaptcha lebal

  • In reCaptcha type you can select same as given in below image.

reCaptcha type

  • In domains setion you can write the default IP of django server as shown in below image.

Domains Section

  • Now, expand Google Cloud Platform dropdown menu and write project name and click on submit.

  • Once you submit, you will get 2 Keys

    • First key will be site key.
    • Second key will be Secret key.

site and secret keys

Configure Public & Private key

  • Copy Site key and paste it in settings.py file in the variable called RECAPTCHA_PUBLIC_KEY.

    RECAPTCHA_PUBLIC_KEY = 'XXXXXXXXXXXXXXXXXXXXXXX'
    
  • Copy Secret key and paste it in settings.py file in the variable called RECAPTCHA_PRIVATE_KEY.

    RECAPTCHA_PRIVATE_KEY = '--XXXXXXXXXXXXXXXXXXXXXXX--'
    

Google reCAPTCHA setting

  • After Copying and Pasting The keys Click on GO TO SETTINGS given below the private key.
  • Check every detail and hit on back arrow button given on the top.

Back button

  • And you should see your console.

reCaptcha console

Creating User creation form

  • In django app folder create file called forms.py.
  • We need to open the file and create a form that allows register new user and we will also add a reCaptcha field.
  • Below is the code for registering new user and adding reCaptcha field.
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# Importing Captcha
from captcha.fields import ReCaptchaField


# create a user
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

    # Adding reCaptcha field    
    captcha = ReCaptchaField()
Enter fullscreen mode Exit fullscreen mode

Creating Views

  • Open views.py file and import some packages.
from django.shortcuts import render, redirect
from .forms import CreateUserForm
Enter fullscreen mode Exit fullscreen mode
  • Write home view function.
def home(request):
    return render(request, 'index.html')
Enter fullscreen mode Exit fullscreen mode
  • Write register view function.
def register(request):
    form = CreateUserForm()

    if request.method == "POST":
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context = {'form': form}
    return render(request, 'register.html', context)
Enter fullscreen mode Exit fullscreen mode

Creating urls for views

  • Open urls.py file in your django app. If you do not have that file then you can create one.
  • Write below code:
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('register/', views.register, name='register'),
]
Enter fullscreen mode Exit fullscreen mode
  • go to urls.py file in django project folder and write below code:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('<your_app_name>.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Templates setup

  • Create templates folder in your django app folder.
  • Create file called base.html in templates folder.
  • Create folder and name it same as your app name.
  • create file called index.html.
  • Below is the code for base.html.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        Security - {% block title %}
        {% endblock title %}
    </title>
</head>
<body>
    {% block content %}
    {% endblock content %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • Below is the code for index.html.
{% extends 'base.html' %}

{% block title %}Home{% endblock title %}

{% block content %}

<nav>
    <a href="{% url 'home' %}">
        &nbsp; Home
    </a>
    <div>


        <ul>
            <li>
                <a type="button" href="{% url 'register' %}">Register</a>
            </li>
            <li>

                <a type="button" href="">Login</a>
            </li>
        </ul>
    </div>
</nav>

<body>
    <br>
    <br>
    <div class="text-center">

        <a class="btn btn-info" type="button" href="{% url 'register' %}"> <i class="fa fa-user" aria-hidden="true"></i>
            &nbsp; Make an account </a>
    </div>
</body>
{% endblock content %}
Enter fullscreen mode Exit fullscreen mode
  • Below is the code for register.html.
{% extends 'base.html' %}

{% block title %}Register User{% endblock title %}

{% block content %}
<div class="container bg-white shadow-md p-5 form-layout">
    <h3>Create Account</h3>
    <h5>Secure your account today!</h5>
    <br>

    <form method="post" autocomplete="off">
        {% csrf_token %}

        {{form}}
        <button type="submit" class="btn btn-info btn-log w-100 btn-block p-3">Create Account</button>
    </form>

    <br><br>

    <div class="text-center">
        {% comment %} <p>Already have an account? </p> <a href="{% url '' %}">Login</a> {% endcomment %}
    </div>
</div>
{% endblock content %}
Enter fullscreen mode Exit fullscreen mode
  • If you wish you can add some bootstrap css.

Finally done with all configuration

  • Now, follow below commands and you will be fine.
  • First, write command to migrate the project python manage.py migrate.
  • Second, write command to start the server python manage.py runserver.

You can also download django code from my GutHub

Thank you <3

This is it for this blog. If you have any doubt please let me know in comments and do not forget to react on this blog and follow me for more amazing content link this.

Top comments (0)