Home / Blogs

How to Implement Social Login in Django – Step-by-Step Guide

Django
·

October 6, 2023

Welcome to the world of Django CAPTCHA! You know those puzzles that prove you’re not a robot? That’s CAPTCHA, and Django, your web ally, makes it a breeze. Our blog takes you through why CAPTCHA matters and how Django weaves this security magic into your site effortlessly. Stick around to discover how CAPTCHA in Django becomes your website’s friendly bouncer, keeping the bad stuff out while letting genuine visitors right in.

Step 1: Setting Up Your Django Project

To get started with Django Social Auth, make sure you have a Django project already set up. If not, follow these simple steps:

Install Django: If you haven’t installed Django yet, open your terminal or command prompt and run the following command to install it:

pip install Django

Create a Django Project: Once Django is installed, navigate to the directory where you want to create your project and run this command to create a new project (replace “myproject” with your preferred project name):

django-admin startproject myproject

Navigate to the Project Directory: Move into the newly created project directory by running:

cd myproject

Create a Django App: Django projects are composed of multiple apps. Create a new app using the following command (replace “myapp” with your desired app name):

python manage.py startapp myapp

Configure Settings: Open the settings.py file inside the myproject folder. Add your newly created app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    # ...
    'myapp',
]

Apply Migrations: Run migrations to create the initial database schema:

python manage.py migrate

Run the Development Server: Start the development server with this command:

python manage.py runserver

You should see output indicating that the development server is running. Open your web browser and navigate to http://127.0.0.1:8000/ to see the default Django welcome page.

To read more about implementing a captcha in Django, refer to our blog How to Implement Captcha in Django in 2023

Step 2: Install Django Social Auth Package

To enable social authentication in your Django project, you’ll need to install the django-social-auth package. This package provides the necessary functionality to integrate with various social media platforms. Here’s how you can install and set it up:

Install the Package: In your project’s terminal, run the following command to install the django-social-auth package:

pip install django-social-auth

Add Social Auth to Installed Apps: Open the settings.py file of your project (myproject folder), and add ‘social_django’ to your INSTALLED_APPS list:

INSTALLED_APPS = [
    # ...
    'social_django',
]

Configure Authentication Backends: In the settings.py file, add the following setting to define the authentication backends for social authentication. Also, include the

AUTHENTICATION_BACKENDS setting to enable social authentication:

AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

This example uses Google OAuth2 as an authentication backend. You can replace ‘social_core.backends.google.GoogleOAuth2’ with the appropriate backend for the social platform you want to integrate.

Include URLs: Add the following URL patterns to your project’s urls.py file to handle social

authentication URLs:

from django.conf.urls import url, include

urlpatterns = [
    # ... other URL patterns ...
    url(r'^social-auth/', include('social_django.urls', namespace='social')),
]

Configuration Settings: Add the following settings to settings.py to customize the behavior of social authentication:

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'your-google-client-id'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'your-google-client-secret'

Replace ‘your-google-client-id’ and ‘your-google-client-secret’ with your actual Google OAuth2 credentials. You can obtain these credentials by creating a project in the Google Developer Console and configuring OAuth2 credentials.

Migrate Database: Apply migrations to update your database schema with the social authentication models:

python manage.py migrate

With these steps completed, you’ve successfully installed the django-social-auth package and configured the basic settings for social authentication in your Django project.

Step 3: Create Views and Templates for Social Authentication

In this step, you’ll create the necessary views and templates to handle social authentication interactions and user login/signup using social accounts:

Create Social Authentication Views: Inside your app’s directory (e.g., myapp), create a new Python file named views.py. Define views for initiating social authentication and handling authentication callbacks:

from django.shortcuts import redirect
from social_django.views import auth, complete

def start_social_auth(request, backend):
    return auth(request, backend)

def complete_social_auth(request, backend):
    return complete(request, backend, redirect_name='next')

Create Templates: Inside your app’s directory, create a folder named templates. Inside the templates folder, create another folder named registration. This is where you’ll store your social authentication templates. For example, create a template named social_login.html for the social login page:

html
Copy code
<!DOCTYPE html>
<html>
<head>
    <title>Social Login</title>
</head>
<body>
    <h2>Social Login</h2>
    <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.GET.next|urlencode }}">Login with Google</a>
</body>
</html>

Update URLs: In your app’s urls.py file, define URLs for your social authentication views:

from django.urls import path
from . import views

app_name = 'myapp'

urlpatterns = [
    # ... other URL patterns ...
    path('social/login/', views.start_social_auth, name='social_login'),
    path('social/complete/<backend>/', views.complete_social_auth, name='social_complete'),
]

Incorporate Social Authentication Templates: In your project’s settings.py file, specify the location of your app’s template folder. Add the following setting:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myapp', 'templates')],
        # ... other settings ...
    },
]

Update Base Template: If your project has a base template (usually named base.html), add a link to the social login page:

<a href="{% url 'myapp:social_login' %}">Social Login</a>

When you click on social login, a pop up will occur, above the picture show’s example of google if the browser has your gmail account, the account will show there, else you can sign in there and  use the gmail account to login to the project

With these steps completed, you’ve created views and templates to handle social authentication interactions. Users can now access the social login page and initiate the authentication process with their social accounts.

Step 4: Handle User Authentication and Data

In this step, you’ll implement the logic to handle user authentication and data after successful social authentication:

Create User Data Handling View: In your app’s views.py file, create a view to handle user data after successful social authentication:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def profile(request):
    return render(request, 'profile.html')

Create Profile Template: Inside your templates folder, create a template named profile.html to display user information:

<!DOCTYPE html>
<html>
<head>
    <title>Profile</title>
</head>
<body>
    <h2>Welcome, {{ user.username }}</h2>
    <p>Email: {{ user.email }}</p>
    <p>Name: {{ user.first_name }} {{ user.last_name }}</p>
</body>
</html>

Update URLs: In your app’s urls.py file, add a URL pattern for the profile view:

urlpatterns = [
    # ... other URL patterns ...
    path('profile/', views.profile, name='profile'),
]

Redirect After Social Authentication: In the settings.py file, specify the URL to redirect users after successful social authentication:

LOGIN_REDIRECT_URL = 'myapp:profile'

User Data Access: To access user data in your templates, make sure you’ve added ‘django.contrib.auth.context_processors.auth’ to your TEMPLATES setting in settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myapp', 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # ...
                'django.contrib.auth.context_processors.auth',
                # ...
            ],
        },
    },
]

Test It Out: Start your development server using python manage.py runserver and navigate to the social login page you created earlier. After successful social authentication, users will be redirected to their profile page, which displays their information.

With these steps completed, users can now authenticate using their social accounts and access their profile information within your Django project.

Horilla Editorial Team Author

Horilla Editorial Team is a group of experienced writers and editors who are passionate about HR software. We have a deep understanding of the HR landscape and are committed to providing our readers with the most up-to-date and informative content. We have written extensively on a variety of HR software topics, including applicant tracking systems, performance management software, and payroll software etc. We are always looking for new ways to share our knowledge with the HR community. If you have a question about HR software, please don't hesitate to contact us.