• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[4 Steps] Django Social Login with Facebook

Aniruddha Chaudhari/10350/5
Django

In this tutorial, you are going to learn how to create a Django social login with Facebook feature for your Django project.

Social login feature can be good add on for many types of project. With simple social login, you can create a membership website, user profile, tracking user behavior, and what not…

At the end of this tutorial you will be able develop User authentication Django project as below.

As you are reading this tutorial, either you are learning to add social login features in Django or you are working on your project where you want to add social login features.

If you are learning, let’s start from scratch and follow this tutorial until the end. If you are really interested to learn, just don’t read. Open your favorite editor or IDE and start developing along with me.

If you already have a Django project where you want to add social login feature, skip step 1. And start from step 2.

Let’s begin.

How to implement Django social login with Facebook feature?

Table of Contents

  • 1. Setting Django Project
  • 2. Install and Set Social Authentication Module
  • 3. Adding Templates and Static Files
  • 4. Facebook Authentication
    • How to access Email ID, Picture from Facebook?

1. Setting Django Project

As I said earlier, if you already have project setup, skip this step.

  • Create one folder/ directory where you will store all source code.
  • Create a virtual environment for your project by running below command in the terminal or command prompt.
$ python -m venv env

I’m not talking about the virtual environment in detail as it is not part of this tutorial. If you are new to the virtual environment, you can read the virtual environment in Python to get a better insight.

  • Now, activate your virtual environment.

For Windows user, open command prompt and run the below command.

$ cd env
$ .\Scripts\Activate

For Linux user, open terminal and run below command.

$ cd env
$ ./Scripts/Activate

Your virtual environment up and running.

  • Install Django in your virtual environment.
$ pip install django

It will install latest Django Python module.

After installation, you can check all the install libraries using pip command.

$ pip freeze

You can see Django project is installed.

asgiref==3.2.7
Django==3.0.5
pytz==2019.3
sqlparse==0.3.1
  • Create your Django project. You can give it any suitable name. For simplicity, I’m naming it as my_project.
$ django-admin startproject my_project
$ cd my_project

You can see new folder is created with the project name.

  • Now create a new Django app for social login and authentication called a prime (You can name it anything).
$ python manage.py startapp prime

Update settings.py to add new app in your project setting.

Add new app in INSTALLED_APPS list.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'prime',  #newly added 
]
  • Start the server with simple command.
python manage.py runserver

If you don’t see any error, your Django server is up and running.

Open browser and run localhost URL.

http://localhost:8000/

Congratulation!

You have installed Django successfully. Your project is up and running.

This step is well explained in Django project tutorial for beginners.

2. Install and Set Social Authentication Module

In this Django social login with Facebook tutorial, we are using the social-auth-app-django Python module for social authentication.

This Python library has already defined all the required functionality for social login. You don’t need to write the functionality from scratch.

  • Install the social-auth-app-django module.
$ pip install social-auth-app-django

If you use pip freeze command it will list all the installed modules where you can see the social-auth-app-django installed on your system. It also installs other dependent modules.

$ pip freeze

asgiref==3.2.7
certifi==2020.4.5.1
cffi==1.14.0
chardet==3.0.4
cryptography==2.9
defusedxml==0.6.0
Django==3.0.5
idna==2.9
oauthlib==3.1.0
pycparser==2.20
PyJWT==1.7.1
python3-openid==3.1.0
pytz==2019.3
requests==2.23.0
requests-oauthlib==1.3.0
six==1.14.0
social-auth-app-django==3.1.0
social-auth-core==3.3.3
sqlparse==0.3.1
urllib3==1.25.8

It also installs Django if it is not installed earlier as a dependency.

Update the INSTALLED_APP in the settings.py to register the library in your project:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'prime',
'social_django', #newly added
]
  • Finally, let’s migrate the database.
py manage.py migrate

When you run this command, you can see all the performed operations on database.

py manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying admin.0003_logentry_add_action_flag_choices… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying auth.0009_alter_user_last_name_max_length… OK
Applying auth.0010_alter_group_name_max_length… OK
Applying auth.0011_update_proxy_permissions… OK
Applying sessions.0001_initial… OK
  • Set the order for authentication.

There can be multiple authentications for the user. Users can login app through different social media applications like Facebook, LinkedIn or Twitter.

You can order these authentication methods. If the first authentication method fails, Django tries the second one, and so on.

By default, there is a single authentication method as

['django.contrib.auth.backends.ModelBackend']

You can check this setting inside settings.py.

Add new authentication methods with your preference order in setting.py.

AUTHENTICATION_BACKENDS = [
  'social_core.backends.facebook.FacebookOAuth2'
  'social_core.backends.linkedin.LinkedinOAuth2',
  'social_core.backends.instagram.InstagramOAuth2,
  'django.contrib.auth.backends.ModelBackend',
]

In the above setting, the order of authentication is Facebook, LinkedIn, Instagram and then django basic authentication.

3. Adding Templates and Static Files

  • Create a new folder “templates” into your app (prime). All the required templates and HTML files will be saved in this folder.
$ cd prime/
$ mkdir templates/

We require three files.

  • base.html
    This is the base file that is used to add header and extend other files.
  • login.html
    This is the login page where users can see all the login options.
  • home.html
    This is the home page where the user will be redirected after login.

Create these three files and save them in the folder “templates”.

You also need style sheet to organize and style content in the HTML files.

  • index.css

Create index.css file inside prime/static/css folder.

Open base.html and copy the below HTML code in the file.

<!-- templates/base.html -->

    {% load static %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
            crossorigin="anonymous" />
        <link rel="stylesheet" href="{% static 'css/index.css' %}" />
        <title>Social Auth with Django</title>
    </head>
    <body>
        <div class="container-fluid">
            <div>
                <h1 class="text-white text-center">{% block title %}{% endblock %}</h1>
                <div class="card p-5">
                    {% block content %}
                    {% endblock %}
                </div>
            </div>
        </div>
    </body>
    </html>

This is simple HTML code.

Open home.html and copy below HTML code into the files.

  <!-- templates/home.html -->

    {% extends 'base.html' %}
    {% block title %} Home {% endblock %}
    {% block content %}
    <div class="row">
        <div class="col-sm-12 mb-3">
            <h4 class="text-center"> Welcome {{ user.username }} </h4>
        </div>
    </div>
    {% endblock %}

Similarly, copy below HTML code for login.html.

<!-- templates/login.html -->

{% extends 'base.html' %}
{% block title %} User Authentication {% endblock %}
{% block content %}
<div class="row">
    <div class="col-md-8 mx-auto social-container my-2 order-md-1">
        <button class="btn btn-primary mb-2">
            <a href="#">Login with Facebook</a>
        </button>
        <button class="btn btn-info mb-2">
                <a href="#">Login with LinkedIn</a>
        </button>
        <button class="btn btn-danger  mb-2">
            <a href="#">Login with Instagram</a>
        </button>
    </div>
</div>
{% endblock %}

You need to add CSS code to style HTML tags. Add below code to index.css.

/_ index.css _/

img {
  border: 3px solid #282c34;
}
.container-fluid {
  height: 100vh;
  background-color: #282c34;
  display: flex;
  justify-content: center;
  align-items: center;
}
.container-fluid > div {
  width: 85%;
  min-width: 300px;
  max-width: 500px;
}
.card {
  width: 100%;
}
.social-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.btn a, .btn a:hover {
  color: white;
  text-decoration: none ;
}

Keep this style sheet as it is right now. Later you can change it as you want.

  • Setting up the Views and URLs.

Open prime/views.py and copy-paste below code into the file.

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

def login(request):
	return render(request, 'login.html')

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

We have to set the URL so that when the user hits the URL, appropriate views will be called.

Set the URL in my_project/urls.py file. Here is code.

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from prime import views

urlpatterns = [
  path('admin/', admin.site.urls),         
  path("login/", views.login, name="login"),
  path("logout/", auth_views.LogoutView.as_view(), name="logout"),
  path('social-auth/', include('social_django.urls', namespace="social")),
  path("", views.home, name="home"),
]

Now you have to set all the required path for user authentication. The social auth module has the following variable defined.

  • LOGIN_URL
    URL for the login page.
  • LOGOUT_URL
    URL for logout page
  • LOGIN_REDIRECT_URL
    URL where user will get redirected after login.
  • LOGOUT_REDIRECT_URL
    URL where user will get redirected after logout.

Open my_project/settings.py file and set these URL variables.

Add the below lines of code at the end of the setting file.

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = 'login'

Wow! Your job is done.

Let’s see how does it work.

Start the project using runserver command.

python manage.py runserver

Opne URL in browser tab.

 http://localhost:8000/

It will redirect you to the login page. which looks like this.

Your job is not yet complete. If you click on any of these button to login, login feature does not work.

You have to authenticate and connect your social media with the Django app.

4. Facebook Authentication

This is the final step in Django social login with Facebook tutorial.

  • Create developer account on Facebook.

Login to your Facebook account in the browser and then open developer account.

Here is the URL for the Facebook developer account.

https://developers.facebook.com/apps
  • Click on Add a New App.
  • Set Display Name and Contact Email for the new app.
  • Click on Create App ID.
  • Open the newly created app.

Go to setting > basics. And set the App Domains as localhost.

set app domains in facebook app

Scroll till the end. You will find the option to set the website. Add the localhost URL in the website field as below.

http://localhost:8000/

Save the changes.

  • Now you need to connect your Facebook app with your Django project.

Copy app ID and secret key. And set those values in social_app/settings.py as below.

SOCIAL_AUTH_FACEBOOK_KEY = YOUR_APP_KRY # App ID
SOCIAL_AUTH_FACEBOOK_SECRET = YOUR_APP_SECRET # App Secret

Update the Facebook login link in login.html.

<button class="btn btn-primary mb-2">
<a href="{% url 'social:begin' 'facebook' %}">Login with Facebook</a>
</button>
  • Run Your Django Project.

Now start web server with below command.

python manage.py runserver

Visit login page in the browser using localhost URL.

localhost:8000/login 

It will look like this in the browser.

Click on Log with Facebook and follow the steps.

After log in, you will be redirected to the home page.

You can see the username which is read from the Facebook profile on the screen.

Here, I log in using my personal Facebook account.

Awesome!

How to access Email ID, Picture from Facebook?

You have to set the parameters that you want to read from the Facebook.

Open setting.py and add following setting.

SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
  'fields': 'id, name, email, picture.type(large), link'
}
SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [
    ('name', 'name'),
    ('email', 'email'),
    ('picture', 'picture'),
    ('link', 'profile_url'),
]

Also add context_processor to access the data.

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',
       'social_django.context_processors.backends', # added
       'social_django.context_processors.login_redirect', # added
     ],
   },
 },
]

In the above setting, we are asking the user to provide an email ID, profile picture, name, and the profile link from the Facebook account.

When a user log in, admin can see all this information inside the admin panel under “user social auth” instance as an “Extra data”.

Update home.html page to display user profile on home page.

<!-- home.html -->

{% extends 'base.html' %}
{% block title %} User Profile {% endblock %}
{% block content %}
<div class="row">
  <div class="col-sm-12 mb-3">
    <h4 class="text-center">Welcome {{ user.username }}</h4>
  </div>

  {% for ass in backends.associated %}
  {% if ass.provider == 'facebook' %}
  <div class="col-md-6 text-center">
    <img src="{{ass.extra_data.picture.data.url}}" alt="" width="150" height="150" style="border-radius: 50%">
  </div>
  <div class="col-md-6 social-container my-2">                 
    <p> You're Signed in via {{ ass.provider }} </p>
    <p> Your Name:  {{ ass.extra_data.name }} </p>
    <p> Profile URL: <a href="{{ass.extra_data.profile_url}}">link</a></p>
  </div>
  {% endif %}
  {% endfor %}
  <div class="col-sm-12 mt-2 text-center">
    <button class="btn btn-danger">
      <a href="{% url 'logout' %}">Logout</a>
    </button>
  </div>
</div>
{% endblock %}
  • Run the Django project again.
python manage.py runserver

Now visit your localhost home page once again (http://localhost:8000/).

You can see all user detail with name, profile picture and link to the Facebook profile.

Awesome!

Conclusion

In this tutorial, you have learned to implement social login authentication in Django using social-auth-app-django Python library.

You can add this social login feature in any of your project where you need to authenticate the user.

This is all about the complete tutorial of Django social login with Facebook. If you have any questions or if you are finding it difficult to implement, let me know in the comment.

Python Interview Questions eBook

Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Tamie
    August 20, 2020 at 1:02 pm

    I’m Tamie. I’m learning Django in my school. Thanks for this tutorial.

  • Reply
    Emperor
    August 8, 2022 at 8:38 am

    Thanks for this tutorial. Does it apply for logging in with Google?

    • Reply
      Aniruddha Chaudhari
      August 8, 2022 at 9:49 am

      You’re welcome, Emperor! Yes, you can implement Google logging similar to the Facebook login demonstrated in the tutorial.

  • Reply
    gianluca
    September 15, 2022 at 10:03 pm

    Hi Aniruddha, i’m Gianluca !! I’m starting to study Python and moving with flask/Django. Your tutorial is what I’m seeking, thanks for sharing 🙂

    • Reply
      Aniruddha Chaudhari
      September 21, 2022 at 10:25 pm

      You’re welcome, Gianluca! I’m glad you are getting help from my tutorial. Hope you enjoy going through my other tutorials as well. Best wishes!

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard