Improve Signup Rates with django-allauth

June 29, 2020, 12:19 p.m.

Django · 7 min read

Improve Signup Rates with django-allauth

What is django-alluth?

Django-alluth is a reusable Django app that allows signups with social accounts, i.e. Facebook, Google, Twitter, Instagram.  Supported features include the ability to signup both local and social accounts as well as a pluggable signup form for additional questions.  Basically, django-alluth will allow you to quickly handle and create signup flows instead of using Django's built-in UserCreationForm.  Below is a list of all supported providers:

  • Amazon (OAuth2)
  • AngelList (OAuth2)
  • Bitly (OAuth2)
  • Dropbox (OAuth)
  • Facebook (both OAuth2 and JS SDK)
  • Feedly (OAuth2)
  • Github (OAuth2)
  • Google (OAuth2)
  • Instagram (OAuth2)
  • LinkedIn (OAuth, OAuth2)
  • OpenId
  • Paypal (OAuth2)
  • Persona
  • SoundCloud (OAuth2)
  • Stack Exchange (OAuth2)
  • Twitch (OAuth2)
  • Twitter (OAuth)
  • Vimeo (OAuth)
  • VK (OAuth2)
  • Weibo (OAuth2)

 

How does django-allauth improve signups?

Most consumers already have at least one of the accounts listed above.  Therefore adding a social login can drastically increase signup rates by alleviating the need for users to create yet another username and password for a website they might not be ready to signup for. Additionally, seeing the Google or Facebook logo as a signup option immediately increases the credibility of a given site while decreasing the time it takes to create an account.  Remember, it's always more difficult to get a user to signup than it is to onboard.  Make the signup process as simple as possible and start onboarding after an account is created, not while the account is being made.  

With plenty of supported providers, django-alluth also allows developers to add the providers that match their target audience.  For example, dev.to only allows users to signup with either a Twitter or Github account.  Given developers' affinity for these platforms, it just makes sense to offer signup options that users are already comfortable with.  As another example, a gaming site might want to implement Twitch signup whereas an e-commerce store could benefit from a Paypal signup. As for our own experience with social logins, simply adding a Google signup button managed to increase our signup rate by roughly 25%.  

Let's go over how we did this.

 

Django Setup

First set up your virtual environment.  Note: For macOS/ubuntu users replace py with python3 

C:\Users\Owner\Desktop\code>py -m venv social

 

Next activate the virtual environment, install Django using a package manager, create a project (mysite), and lastly create an app (main).

C:\Users\Owner\Desktop\code>cd social

C:\Users\Owner\Desktop\code\social>Scripts\activate

(social) C:\Users\Owner\Desktop\code\social>pip install Django

(social) C:\Users\Owner\Desktop\code\social>django-admin startproject mysite

(social) C:\Users\Owner\Desktop\code\social>cd mysite

(social) C:\Users\Owner\Desktop\code\social\mysite>py manage.py startapp main

 

Add the main app to INSTALLED_APPS in settings.py.

mysite/settings.py

INSTALLED_APPS = [
    'main.apps.MainConfig', #add this
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

Create a superuser to login to the Django admin.

(social) C:\Users\Owner\Desktop\code\social\mysite>py manage.py createsuperuser

 

Make migrations and migrate.

(social) C:\Users\Owner\Desktop\code\social\mysite>py manage.py makemigrations
...
(social) C:\Users\Owner\Desktop\code\social\mysite>py manage.py migrate

 

Install django-alluth with your package manager.  Then add django-alluth to INSTALLED_APPS in settings.py and include multiple authentication backends.  Also, add a redirect URL to specify where users will be redirected to after signing in with social authentication.

(social) C:\Users\Owner\Desktop\code\social\mysite>pip install django-allauth

 

mysite/settings.py

INSTALLED_APPS = [
    'main.apps.MainConfig', 
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #add the following
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount', 


]

AUTHENTICATION_BACKENDS = (
 #used for default signin such as loggin into admin panel
 'django.contrib.auth.backends.ModelBackend', 
  
 #used for social authentications
 'allauth.account.auth_backends.AuthenticationBackend',
 )

SITE_ID = 1

LOGIN_REDIRECT_URL = '/tutorials'

 

Include allauth.urls in mysite/urls.py.

mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
]

 

Signup with Google

Add the provider-specific settings to settings.py.

mysite/settings.py

INSTALLED_APPS = [
    'main.apps.MainConfig', 
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount', 

    'allauth.socialaccount.providers.google', #for google auth

]

...


SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}

 

Migrate the changes.

(social) C:\Users\Owner\Desktop\code\social\mysite>py manage.py migrate

 

Alright, let's set up a registration page.  First, create a new urls.py file in the main app and include the URLs in mysite/urls.py.

main/urls.py

from django.urls import path
from . import views

app_name = "main"   

urlpatterns = [
	path("", views.homepage, name="homepage"),
	path("register", views.register, name="register"),

]

mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('main.urls')),
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
]

 

Add the appropriate view functions to views.py.  Notice that we are setting up the traditional registration form as well.  However, we also need to specify the correct backend from our settings.

main/views.py

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate, logout

def homepage(request):
	return render(request, "home.html")

def register(request):
	if request.method == "POST":
		form = UserCreationForm(request.POST)
		if form.is_valid():
			user = form.save()
			username = form.cleaned_data.get('username')
			messages.success(request, f"New account created: {username}")
			login(request, user, backend='django.contrib.auth.backends.ModelBackend')
		else:
			messages.error(request,"Account creation failed")

		return redirect("main:homepage")

	form = UserCreationForm()
	return render(request,"register.html", {"form": form})


 

Create a register.html template.  In the template, we will add both the traditional registration form as well as the Google signup.  Note: we also use django-crispy-forms to render our registration form.  Follow this guide to learn more.

templates/register.html

{% extends "home.html" %}

{% block content %}

{% load crispy_forms_tags %}
{% load socialaccount %}
{% load static %}

<div class="container mx-5">


	<div class=" signin text-center">

		<a href="{% provider_login_url 'google' %}" class="text-dark"><img src="{% static "btn_google_signin_light_normal_web@2x.png" %}" style="width:14rem; height:auto"></a>
	</div>

	<br><br>

	<div style="width: 100%; height: 15px; border-bottom: 1px solid lightgray; text-align: center">
		<span class="text-muted" style="margin-top:-15% !important; font-size: 11px; background-color: white; padding: 0px 10px;">
			OR
		</span>
	</div>

	<br><br>

	<form method="post">
		{% csrf_token %}
		{{ form|crispy }}
		<button type="submit"  class="btn btn-primary">Register</button>

	</form>

</div>

{% endblock %}

register with Google

 

Awesome, now we just need to login to the admin panel with our previously created superuser, get our Google OAuth credentials, and add the appropriate information.  After logging in, click "Social Applications" at the bottom of the admin panel and then click "Add Social Application".

add social application

 

Before we can enter this information we need to get our Google OAuth credentials.  Visit the Google Developers Console.  Go to Credentials in the side navbar.  To create credentials you will first need to create a new project and consent form. Click "CREATE PROJECT", enter a name related to your web app, and hit create.  Next, you will be prompted to fill out the OAuth Consent Form.  Select "External" so any user can signup via Google OAuth.  Enter a related name for your app and an email.  Only these fields are required.  Finally, go back to Credentials, click Create Credentials, and select OAuth Client ID.

google oauth credentials

 

Select "Web Application", enter a name, and specify the origin and redirect URI's.  In our case, since we are working on our development server, we'll enter http://127.0.0.1:8000/ as our origin URI and http://127.0.0.1:8000/accounts/google/login/callback/ as our redirect URI.  We previously added this path to mysite/urls.py when we included allauth.urls.  

create client id

 

Click "Create" to receive your client ID and client secret.  Go back to your Django admin page, select "Google" as the provider, enter "Google" as the name, enter the client ID, enter the secret key, and finally add the example.com site

Go back to your registration page and click the "Sign with Google" button.  You should be redirected to the available Google sign-in options.  Select one to create an account and sign in via Google OAuth.  To check that you are currently signed in as the new user, visit the admin page which should prompt you that the user is not allowed, or enter the following code on you home.html template:

      {% if user.is_authenticated %}
        <h2 class="text-center">{{ user.username }}</h2>
      {% endif %}

 

Make sure to abide by the providers' rules governing logo use and placement for your social authentication buttons.  For production, swap out your local server address with the domain you are using.  


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments