How to implement social Login for Django app

In this article we will get to know about how to login to your django app by using social logins like Facebook and Google.

Start a simple Django project


 

Running ./manage.py syncdb and then ./manage.py runserver and navigating to localhost:8000 will show the familiar “It worked!” Django page. Let’s put some custom application code in place, so that we can tell whether the current user is authenticated or anonymous.

Show current user’s authentication status

Now, the very small customizations we’ll add are:

Relevant portion of settings.py:


 

Template: thirdauth/base.html:

Template: thirdauth/home.html:

File views.py:


 

File urls.py:


 

Install Python Social Auth

Second, let’s make some modifications to our settings.py to include python-social-auth in our project:


 

Lets update the urls module to include the new group of URLs:


 

And finally, let’s update the database models:

./manage.py syncdb

Add links for logging in and logging out.

Since we’ll be logging in and out multiple times, let’s include django.contrib.auth URLs into our URLs configuration:


 

Let’s modify our Home page template like this:

For the login and logout links in this template to work correctly, we need to modify a few things. First, let’s take care of logout, it’s easier. Just add ‘request’ to the context object that we pass into template-rendering code.

Updated views.py:


 

For login to work, let’s first add a LOGIN_REDIRECT_URL parameter to settings (to prevent the default /account/profile from raising a 404):

LOGIN_REDIRECT_URL = ‘/’

Get Client IDs for the social sites.

For All the social networks we are using in this demo, the process of obtaining an OAuth2 client ID (also known as application ID) is pretty similar. All of them will require that your application has a “real” URL – that is, not http://127.0.0.1 or http://localhost. You can add an entry in your /etc/hosts file that maps 127.0.0.1 to something like “test1.com”, and the URL of your application becomes http://test1.com:8000 – that is good enough for testing. You can change it in the social app settings when it goes into production.

Facebook:

Google:

 

Leave a Reply

Your email address will not be published. Required fields are marked *