DEV Community

Andrés Álvarez Iglesias
Andrés Álvarez Iglesias

Posted on

Django AllAuth Chapter 2 - How to install and configure Django AllAuth

In this chapter we'll explore the basics of the AllAuth extension: from the installation to a basic usage for a login/password based access to our Django app. Let's go!

(NOTE: First published in my Substack list: https://andresalvareziglesias.substack.com/)

List of chapters

  • Chapter 1 - The All-in-one solution for Auth in Django
  • Chapter 2 - How to install and configure Django AllAuth ←This one!
  • Chapter 3 - Social login with Django AllAuth
  • Chapter 4 - Customizing Django AllAuth UI
  • Chapter 5 - Extending Django AllAuth user model with custom fields

Image description

Installation of AllAuth

As any other Django extension, AllAuth installation has two parts: install the python dependencies and configure the Django app settings file. To make things more fun, we will use (and learn) Google Project IDX, a wonderful cloud IDE and development platform.

First, log into IDX and create a new Django based project:

Image description

Once created, we will have a fully working Django app, so move on!

The installation of AllAuth itself is simple: just install the django-allauth python package. Project IDX (and ourselves, in case of manual project creation) creates a requirements.txt file, so let's use it:

  • Add "django-allauth" to dependencies.txt. You can also add "django-allauth[socialaccount]", used in the next chapter for social login
  • Open the IDX terminal and navigate to dependencies.txt parent folder
  • Load the virtual environment created with out project by IDX: source ~/allauth-test/.venv/bin/activate
  • Execute: pip install -r requirements.txt

Now, we need to make some changes to the main Django app settings file. Open settings.py and locate the TEMPLATES setting. Add the AllAuth required processor:

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',

               # This one                
               'django.template.context_processors.request',
           ],
       },
   },
]
Enter fullscreen mode Exit fullscreen mode

Then, locate the AUTHENTICATION_BACKENDS setting and add the AllAuth backend. If not present, add it now:

AUTHENTICATION_BACKENDS = [
   # Needed to login by user in admin, regardless of `allauth`
   'django.contrib.auth.backends.ModelBackend',

   # This one
   'allauth.account.auth_backends.AuthenticationBackend',
]
Enter fullscreen mode Exit fullscreen mode

Next, add AllAuth to installed apps as any other Django extension. You can also add the social login extensions here, used in the next chapter:

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

   # Add these
   'allauth',
   'allauth.account',
   'allauth.socialaccount',
   'allauth.socialaccount.providers.google',
]
Enter fullscreen mode Exit fullscreen mode

The last modification of the settings file is the required middleware. Locate the MIDDLEWARE section and add the AllAuth middleware at the end:

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',

   # This one
   "allauth.account.middleware.AccountMiddleware",
]
Enter fullscreen mode Exit fullscreen mode

AllAuth has it own views, templates and databases, so we need to perform some extra actions. The first action is to define the URLs for AllAuth views. Open the main urls.py and add them:

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

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

Now, the code modifications are completed, but we need to create AllAuth required tables. Use the Django migration tool from the IDX terminal, navigating to manage.py location and executing:

python3 manage.py migrate
Enter fullscreen mode Exit fullscreen mode

We also need an administrator to test the login (and to create users). Create it now:

python3 manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Testing AllAuth installation

Now, we have a fully working AllAuth installation. To test the authentication methods, create a demo app with manage.py:

python3 manage.py startapp demo
Enter fullscreen mode Exit fullscreen mode

Register it in the INSTALLED_APPS section of the main settings page:

INSTALLED_APPS = [
   (...)

   'allauth',
   'allauth.account',
   'allauth.socialaccount',
   'allauth.socialaccount.providers.google',

   # This one
   'demo'
]
Enter fullscreen mode Exit fullscreen mode

And map it to main urls.py file:

urlpatterns = [
   path('', include('demo.urls')),
   path('admin/', admin.site.urls),
   path('accounts/', include('allauth.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Then, create a simple view in our new demo app:

from django.shortcuts import render
from django.http import HttpResponse

def indexView(request):
   if request.user.is_authenticated:
      return HttpResponse("""
         <span style='color: green;'>Logged in</span>
         """)
   else:
      return HttpResponse("""
         <span style='color: red;'>Not logged in</span>
         """)
Enter fullscreen mode Exit fullscreen mode

And map it to demo's urls.py:

from django.contrib import admin
from django.urls import path, include
from demo.views import indexView

urlpatterns = [
   path('', indexView, name='indexView'),

   # Override default postlogin action with our view
   path('accounts/profile/', indexView, name='profileOverridenView'),
]
Enter fullscreen mode Exit fullscreen mode

And now, load the page in IDX’s viewer:

Image description

We can use now AllAuth views to perform authentication. For example, use /accounts/login endpoint to perform a login with the previously created user:

Image description

And then, we will receive the expected login page:

Image description

You can also use other useful AllAuth views, like:

  • Signup: /accounts/signup/
  • Login: /accounts/login/
  • Logout: /accounts/logout/
  • Change password: /accounts/password/change/

Simple and easy!

About the list

Among the Python and Docker posts, I will also write about other related topics (always tech and programming topics, I promise... with the fingers crossed), like:

  • Software architecture
  • Programming environments
  • Linux operating system
  • Etc.

If you found some interesting technology, programming language or whatever, please, let me know! I'm always open to learning something new!

About the author

I'm Andrés, a full-stack software developer based in Palma, on a personal journey to improve my coding skills. I'm also a self-published fantasy writer with four published novels to my name. Feel free to ask me anything!

Top comments (0)