# Django User Registration with Google

**URL:** <http://fluxxset.com/t/django-user-registration-with-google/495>\
**Category:** sys admin\
**Tags:** django, google\
**Created:** [February 9, 2025, 7:28am UTC](http://fluxxset.com/t/django-user-registration-with-google/495 "2025-02-09T07:28:09Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ServerGuyFluxx](http://fluxxset.com/user_avatar/fluxxset.com/serverguyfluxx/32/12_2.png) [@ServerGuyFluxx](http://fluxxset.com/u/ServerGuyFluxx)\
**Post date:** [February 9, 2025, 7:28am UTC](http://fluxxset.com/t/django-user-registration-with-google/495/1 "2025-02-09T07:28:09Z")

</div>

Credit : [KellyKiiru](https://github.com/KellyKiiru)

OAuth, short for Open Authorization, is a mechanism that enables websites or applications to exchange user data with other platforms, all without necessitating the disclosure of a user’s password. It empowers users to access multiple websites with a single set of login credentials.

Prominent OAuth service providers include Google, Facebook, and GitHub. In this tutorial, we will explore the process of user registration within a Django application using Google OAuth as our chosen authentication method.

# Prerequisites

To follow along with this article, you will need to have the following:

A [GitHub](https://github.com/)account.

[Python](https://www.python.org/downloads/), [pip](https://pip.pypa.io/en/stable/installation/) and [Django](https://docs.djangoproject.com/en/4.2/topics/install/) installed

Visual Studio Code — Integrated Development Environment(IDE)

# Step 1 — Create and set up a new Django project

Create a folder(directory) and name it google-Oauth. Inside of this folder create a virtual environment:

`python -m venv venv`

You can name your virtual environment anything. In this case, I named it ‘venv’.

For Windows OS activate the virtual environment using:

`venv\Scripts\activate`

For Linux and mac OS use:

`source venv/bin/activate`

Or:  
. venv/bin/activate

On activation, install django:

`pip install django`

Create a django project:

`django-admin createproject auth_project .`

Create a django app:

`django-admin createapp auth_app`

Add ‘auth\_app’ to the INSTALLED\_APPS array:

 ![image](http://fluxxset.com/uploads/default/original/1X/efccc34a0da81c500245921ef3c8361c870bc29a.png)

Apply and migrate this changes to SQLite:

```auto

python manage.py migrate

```

 ![image](http://fluxxset.com/uploads/default/original/1X/603ffb359fa258949945ea8a179c2b21bfb412f3.jpeg)

Step 2 — Install and set up django-allauth  
`Install the django-allauth`

pip install django-allauth  
Add it to the INSTALLED\_APPS array:

```auto

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites', //add this line too

    'auth_app',

    //all auth configurations
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google'
]

```

The last item of this array specifies the _django-allauth_ provider you will use which in this case is google. _django-allauth_ also supports other [providers](https://django-allauth.readthedocs.io/en/latest/).

Add AUTHENTICATION\_BACKENDS to settings.py at the bottom of your page:

```auto
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend'
]

```

Add `SOCIALACCOUNT_PROVIDERS` configurations array to settings.py:

```auto
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE' : [
            'profile',
            'email'
        ],
        'APP': {
            'client_id': os.environ['CLIENT_ID'],
            'secret': os.environ['CLIENT_SECRET'],
        },
        'AUTH_PARAMS': {
            'access_type':'online',
        }
    }
}

```

The SCOPE outlines the required parameters for Google APIs. In the absence of a specified scope, it will default to ‘profile.’ To enable background authentication refresh, configure AUTH\_PARAMS[‘access\_type’] as ‘offline.’

Add SITE\_ID and redirect users to the base route after a successful login or logout.

```auto
SITE_ID = 2

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

```

# Step 3 — Create and configure templates

In this project we will use django templates to view our code. In _auth\_app,_ create a folder called ‘templates’. Django has an inbuilt mechanism that will find this templates folder.

Replace this TEMPLATES array in settings.py:

```auto
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

```

with:

```auto
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'], //updated line
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

```

Inside of ‘templates’ folder in _auth\_app_ create an _index.html_ file.

Add the following code to it:

```auto
{% load socialaccount %} //make sure to add this
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 style="text-align: center;"> My google OAuth Project </h1>
    {% if user.is_authenticated %}
    <p>Welcome. You are logged in as {{user.username}} </p>
    {% else %}
    <a href="{% provider_login_url 'google' %}">Login with Google</a>
    {% endif %}
</body>
</html>

```

# Step 4 — Configure Project URLs

Inside of auth\_project/urls.py define the urlpatterns:

```auto
from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView // useful in displaying index.html template
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app/',include('auth_app.urls')), //app_auth urls

    path('', TemplateView.as_view(template_name='index.html')),
    path('accounts/', include('allauth.urls')), // all OAuth operations will be performed under this route
    path('logout', LogoutView.as_view()) // default Django logout view at /logout
]

```

# Step 5— Create and configure a new Google APIs project

Head over to [google developer APIs console](https://console.cloud.google.com/apis/dashboard?project=circular-truth-396321) and navigate to NEW PROJECT under ‘select project’

 ![image](http://fluxxset.com/uploads/default/original/1X/796dffe0485e0cfb98d8e47972aa338935480907.png)  
Set your app name and user support email in the OAuth Consent Screen  
 ![image](http://fluxxset.com/uploads/default/original/1X/d6db3444e497fe7d362ca3dd73615d292fcadbb4.jpeg)  
Switch to the Credentials tab and configure the following.

Note that its http and not https.

 ![image](http://fluxxset.com/uploads/default/original/1X/c2a15317f0bb48e39916afae7daa34c33c3f7af9.png)  
At this point create a .env and a .gitignore file in the root folder (google-Oauth) of your application. We will store our environment variables(secrets) in this file.

In your .gitignore file add the following lines. This will prevent git from pushing this code to GitHub as this folders will be ignored.

```auto
venv/
/.env

```

In your .env add the following:

 ![image](http://fluxxset.com/uploads/default/original/1X/ab3620877670dbd27a7659ba9a103495b43b5ed7.png)

This will be found in the Credentials tab:

 ![image](http://fluxxset.com/uploads/default/original/1X/8e2dda64fc6bfc64c0897b5d3c19087ecc2db9bf.png)

To access the environment variables download [load\_dotenv](https://pypi.org/project/python-dotenv/) from pip

```auto
pip install python-dotenv

```

In settings.py add this

```auto
import os
from pathlib import Path
from dotenv import load_dotenv

load_dotenv()

```

This will make it possible for django to locate the environment variables. In this case:

```auto
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE' : [
            'profile',
            'email'
        ],
        'APP': {
            'client_id': os.environ['CLIENT_ID'], // in .env file
            'secret': os.environ['CLIENT_SECRET'], // in .env file
        },
        'AUTH_PARAMS': {
            'access_type':'online',
        }
    }
}

```

Migrate this configurations:

```auto
python manage.py migrate

```

# Step 6— Configuring admin site

Create super user:

```auto
python manage.py createsuperuser

```

Follow the prompts to create the superuser.

Run the server

```auto
python manage.py runserver

```

In your browser, open [http://127.0.0.1:8000/admin](http://127.0.0.1:8000/admin) and login with the superuser details and set the _domain_ as well as _display_ names like this.

 ![image](http://fluxxset.com/uploads/default/original/1X/9ee9c39340554510733cda7587baa42e0a5974a6.png)

Select social applications tab and configure it like this:

 ![image](http://fluxxset.com/uploads/default/original/1X/6ad5412c7d9979405e6b90ecff8a4639c85cdceb.png)

To test out if the installation was successful, log out on the top right and log in again but with google this time.

Since django already has a pre-made site([example.com](http://example.com)) as seen above. The SITE\_ID setting in settings.py might bring errors if its value is 1. Makes sure its value is 2.

`SITE_ID = 2`

On logging out, log in with google, your application will ask you to do so with your google account. This information will be saved in your auth\_user table of your database. You can also confirm this by checking [http://127.0.0.1:8000/admin/socialaccount/socialaccount/](http://127.0.0.1:8000/admin/socialaccount/socialaccount/)

# Conclusion

In this article, you learned how to start and configure a django project as well as adding Google Oauth for auth\_users.  
You configured your [google developer APIs console](https://console.cloud.google.com/apis/dashboard?project=circular-truth-396321) with the right details.

The code is available on [GitHub](https://github.com/KellyKiiru/googleOauth). I hope this article was beneficial to you. If so, leave a github star.

Happy coding.
