Geek Culture
Published in

Geek Culture

Django Social Authentication: Sign In With Facebook

How to sign in and sign up using Facebook in Django web apps

Login with Facebook Using Django Framework

Hello, Django Developers..!!

My name is Rohit Kumar Thakur. I generally write about React Native, Django, Data Science, Machine Learning, and Python.

In this article, I am going to show you how to use social authentication in Django applications. When you are building a web application, then adding Facebook authentication is the most common feature you can add. It will help users to log in to your website easily. So, without wasting any time let’s start this project.

Here is the step by step video tutorial of this article:

Project Setup

  • I always suggest starting a Django project in a virtual environment because it’s a good habit to practice.
  • Choose a directory. Open the terminal or command prompt window in that directory and start a virtual environment. Activate that virtual environment. I wrote a separate article on how to start a virtual environment in Windows and Linux. You can check if you need help.
  • After activating the virtual environment, install the following python library:
pip install django
pip install social-auth-app-django
  • Start a Django project:
django-admin startproject facebook
cd facebook
python manage.py startapp mainApp
  • Open this project in your favorite text editor. I mean VS Code. xd:)

Code

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django', #add this
'mainApp', #add this
]MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', #add this
]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', #add this
],
},
},
]
#Add this at the bottom in settings.py
#social app custom settings

AUTHENTICATION_BACKENDS = [
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
]
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = 'login'
SOCIAL_AUTH_FACEBOOK_KEY = "#############"
SOCIAL_AUTH_FACEBOOK_SECRET = "############"
#for extra info
SOCIAL_AUTH_FACEBOOK_SCOPE = [
'email',
]

In the settings.py. We need to add a few lines of code to INSTALLED_APPS, MIDDLEWARE, and TEMPLATES sections. After that, we have to add a few lines of code at the bottom as shown above.

views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.def login(request):
return render(request, 'login.html')
@login_required
def home(request):
return render(request, 'home.html')

In views.py, first, we are going to import all the required libraries. After that, write two functions to render the login and home screen.

Now inside the mainApp directory. Make a new directory “templates”. Inside the templates directory, make three new files: base.html, login.html, home.html

Make a static folder too. Inside the mainApp directory. And inside the static directory, make a file “index.css

You can customize the CSS part on your own if you want. But for a minimal UI reference, you can add the following codes to the index.css file.

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

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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'index.css' %}" />
<title>Django Social Auth</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 the code of the base.html file. We are going to take reference and relative tag elements in login.html and base.html.

login.html

{% extends 'base.html' %}
{% block title %}Sign in {% 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="{% url 'social:begin' 'facebook' %}">Login With Facebook</a>
</button>
</div>
</div>
{% endblock %}

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 %}

This is the basic code of login and home screen. After the successful login, we are going to display the name of the user on the home screen.

facebook/urls.py

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from mainApp 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'),
]

Add the URLs in the main directory.

Configure Facebook Developer Console

Now we have to do only one thing. Let’s set up Facebook Developer Account. I recommend you watch the video after 19:42. The video is here.

  • Search Facebook for developers or Meta for developers
  • Click on Get started
  • Make sure you have an active Facebook account.
  • Register your app by clicking continue.
  • Add your details like phone, and email. Click continue
  • Select student or developer and complete your registration.
  • Click on create an app
  • Select consumer and click on continue.
  • Display name: “Test App”
  • Enter your Facebook password and create your app
  • Click settings -> Basic
  • App domains: localhost
  • Privacy policy URL: http://example.com/
  • Data deletion URL: https://example.com/
  • Click on save changes
  • Scroll down and click on Add platform
  • Select the website and click on next
  • Site URL: http://localhost:8081/
  • Click on save changes
  • Copy the client app id and client app secret and past it here
SOCIAL_AUTH_FACEBOOK_KEY = "#############"
SOCIAL_AUTH_FACEBOOK_SECRET = "############"
  • If you checked the video then make sure to hit the subscribe button. I make cool Django and react native applications. Your support will be admired.

* **Make sure that you log in to the same Facebook profile in the same chrome profile browser. This means that you can’t test this app on other Facebook profiles because of the Facebook privacy policy and we are using this app in our localhost.

Now, Open your terminal or command prompt and migrate the Django application.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now click on the “Login with Facebook” button. You are good to go now.

Github Code Link

Now, clap, clap and clap! And do follow for more project-based articles on Django Framework.

Thanks for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store