Django - reCaptcha
Tags: django, googlecloud, security, tutorial
Published: 2023-07-23 09:35:04

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?"](https://dev.to/yashpatel_py/what-is-django-3i6b).

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](https://pypi.org/project/django-recaptcha/#installation).
- 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)](https://www.google.com/recaptcha/about/)

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

- In label section you can right any label name.

![reCaptcha lebal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7px2b75xt05ka6cqd1d.png)

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

![reCaptcha type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3lb6hfpqejjggq5do3q.png)

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


![Domains Section](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5p7e4f3ou1v2itogzw4m.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7ipctc9eav02u0xrbqj.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewszb2jc072v2xitpz8i.png)

- And you should see your console.

![reCaptcha console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7sz3e6arzki2ezwp22i.png)

## 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>
<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>
```
- 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 %}
<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 %}
```
- 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.