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'. ```python

INSTALLED_APPS = [
...,
'captcha',
...
]


- Now add reCaptcha `public` and `private` key `settings.py`.
    ```python


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. ```python

RECAPTCHA_PUBLIC_KEY = 'XXXXXXXXXXXXXXXXXXXXXXX'


- Copy `Secret key` and paste it in `settings.py` file in the variable called `RECAPTCHA_PRIVATE_KEY`.
    ```python


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. ```python

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()

## Creating Views
- Open `views.py` file and import some packages.
```python


from django.shortcuts import render, redirect
from .forms import CreateUserForm


  • Write home view function. ```python

def home(request):
return render(request, 'index.html')


- Write register view function.
```python


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)


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: ```python

from django.urls import path
from . import views

urlpatterns = [
path('', views.home, name='home'),
path('register/', views.register, name='register'),
]

- go to urls.py file in django project folder and write below code:
```python


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')),
]


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. ```html

<!DOCTYPE html>






Security - {% block title %}
{% endblock title %}



{% block content %}
{% endblock content %}

- Below is the code for `index.html`.
```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 %}


  • Below is the code for register.html. ```html

{% extends 'base.html' %}

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

{% block content %}

<h3>Create Account</h3>
<h5>Secure your account today!</h5>
<br>


    {% csrf_token %}

    {{form}}
    Create Account


<br><br>


    {% comment %} <p>Already have an account? </p> <a href="%20url%20''%20">Login</a> {% endcomment %}
Enter fullscreen mode Exit fullscreen mode

{% endblock content %}

- 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](https://github.com/yashpatel-py/django_recaptcha)

## 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)