Accounts with django-allauth
Categories:
14 minute read
Since Prep 06, your locallibrary has accounts from django-allauth: people sign up with a username, email and password, verify their email address, and log in with either the username or the email address. What nobody can do yet is log in with an account they already have somewhere else. allauth handles that too, through social account providers such as Google.
In this activity you’ll let people sign up and log in two more ways:
- with their Google account, through a Google Cloud project of your own
- with their JMU Canvas account, through allauth’s OpenID Connect provider. This part stays switched off until your professor gives you a client ID and secret.
Then you’ll give users fields of your own, see what your Django Ninja APIs need, and finally, if you have time left over, look at how allauth’s pages can be restyled.
Before you start
You need to have completed Prep 06 (Parts 7 and 8 of our fork of the MDN Django Tutorial). Your locallibrary has django-allauth installed, its pages at /accounts/ (from include('allauth.urls')), and a sidebar that shows Login and Sign up links or a Logout button.
If you’ve also done our Django Ninja Quickstart or our Django Ninja Tutorial, The API section says what changes for them. If you haven’t, skip it.
Every command is run from the root of your locallibrary repository, the folder with manage.py.
This activity was checked on 2026-10-23 with django-allauth 65.20.1, Django 6.1 and Python 3.14.
Install
allauth’s social login support is an extra: it needs a few more packages, which [socialaccount] installs along with it:
uv add "django-allauth[socialaccount]"
Settings
In locallibrary_config/settings.py, add allauth’s social account app, and one provider app for each kind of social login, to INSTALLED_APPS, after the two allauth apps you added in Prep 06:
# locallibrary_config/settings.py
INSTALLED_APPS = [
# ... everything that's already here, ending with:
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.openid_connect',
]
Everything else allauth needs (the middleware, the authentication backend, and the ACCOUNT_... settings) is already there from Prep 06. You don’t need to change your URLs either: include('allauth.urls') adds the social login pages on its own, under /accounts/.
Create the social account tables:
uv run python manage.py migrate
Your login page doesn’t show any social login buttons yet, because no provider is configured. That’s next.
Log in with Google
Logging in with Google is OAuth 2.0 with OpenID Connect: your site sends the user to Google, Google asks them to agree, and then sends them back to your site with a code that your server trades for their identity. For that, Google needs to know about your site, and you need a client ID and client secret from Google.
Create the credentials
Use the Google Cloud account you have course credits on. Signing in with Google doesn’t cost anything. The console’s menus get renamed every so often. If yours look different from the steps below, follow allauth’s Google provider page.
- In the Google Cloud console, create a project for your locallibrary, or pick one you have.
- Go to Google Auth Platform (also listed as APIs & Services → OAuth consent screen) and click Get started. Give the app a name, such as “LocalLibrary”, choose your email address as the support email, choose External as the audience, and finish.
- Under Audience, the app is in Testing mode, so only the test users you list can sign in. Add your own Google account, and anyone else you want to try it, as test users.
- Under Clients, click Create client. Choose Web application, and add these Authorized redirect URIs:
http://127.0.0.1:8000/accounts/google/login/callback/http://localhost:8000/accounts/google/login/callback/
- Click Create, and copy the Client ID and the Client secret.
The redirect URI is where Google sends people back to, and it must match exactly, down to the trailing slash. Google only accepts http:// for localhost and 127.0.0.1. When you deploy, add your site’s https:// URL as another redirect URI.
Keep the secret out of git
The client secret is a password for your Google app. It doesn’t go in settings.py, which is in git. Your settings.py already reads a .env file at the top, with env = environ.Env(), and .env is in your .gitignore. Add your credentials to .env:
# .env
GOOGLE_CLIENT_ID=1234567890-abc123.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=GOCSPX-...
Add the same names, without the values, to .env.example, which is in git, so that anyone who clones your repository knows which settings to provide:
# .env.example
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
Configure the provider
At the bottom of settings.py, add:
# locallibrary_config/settings.py
SOCIALACCOUNT_PROVIDERS = {}
GOOGLE_CLIENT_ID = env.str('GOOGLE_CLIENT_ID', default='')
if GOOGLE_CLIENT_ID:
SOCIALACCOUNT_PROVIDERS['google'] = {
'APPS': [
{
'client_id': GOOGLE_CLIENT_ID,
'secret': env.str('GOOGLE_CLIENT_SECRET'),
},
],
'SCOPE': ['profile', 'email'],
'OAUTH_PKCE_ENABLED': True,
}
APPSholds the credentials. allauth’s documentation also shows the admin’s Social applications page as a way to enter them. Either works, but settings read from.envkeep the secret out of your database and out of git, and they work the same on every machine you run the project on.if GOOGLE_CLIENT_ID:leaves Google out entirely when there’s no client ID, for example on a classmate’s clone without a.env. With no app configured, allauth just doesn’t show the button.SCOPEasks Google for the user’s name, picture and email address.OAUTH_PKCE_ENABLEDadds PKCE, which protects the code on its way back to your site.
Try it
Restart the server, so it reads .env again, and log out. The login page now shows Google under “Or use a third-party”. Click it, then Continue, and pick your Google account.
The first time, allauth creates a new user for you. Google says your email address is verified, so you don’t get a confirmation email, and your username is made up from your name or email address. Log out and log in with Google again, and you’re back in the same account: allauth remembers which Google account belongs to which user. In the admin, Social accounts lists the connection.
Use 127.0.0.1 in your browser if you registered 127.0.0.1 as the redirect URI. If Google shows redirect_uri_mismatch, the address in your browser isn’t one of the redirect URIs you registered.
Log in with JMU Canvas
Canvas can also tell your site who someone is. allauth has no Canvas provider, but Canvas speaks OpenID Connect (OIDC), the standard that Google’s login is built on, and allauth’s openid_connect provider works with any OIDC server.
Your professor creates Canvas’s equivalent of a Google client, a developer key, and gives you its client ID and secret. Until you have them, this provider stays switched off, and your site works without it.
What Canvas says about itself
An OIDC server describes itself in a discovery document, at /.well-known/openid-configuration. Open https://canvas.jmu.edu/.well-known/openid-configuration:
{
"issuer": "https://canvas.jmu.edu",
"authorization_endpoint": "https://canvas.jmu.edu/login/oauth2/auth",
"token_endpoint": "https://canvas.jmu.edu/login/oauth2/token",
"jwks_uri": "https://canvas.jmu.edu/login/oauth2/jwks",
"scopes_supported": ["openid"],
"claims_supported": ["sub"],
...
}
allauth reads this document to find out where to send people, and where to trade the code for a token. Two things are different from Google’s discovery document:
- Canvas only supports the
openidscope, and the only thing it says about a user issub, an ID. There’s noprofileoremail. - There’s no
userinfo_endpoint, the URL that a client asks for more about the user. allauth asks the userinfo endpoint by default.
Canvas’s own REST API knows more about the user: /api/v1/users/self returns the logged-in user’s Canvas ID and name. allauth’s openid_configuration_overrides setting lets you fill in what the discovery document leaves out, so you can tell allauth to use that API as the userinfo endpoint.
Configure the provider
Add these names to .env.example:
# .env.example
CANVAS_ENABLED=False
CANVAS_CLIENT_ID=
CANVAS_CLIENT_SECRET=
and copy them into your .env, with CANVAS_ENABLED=False for now. Then add the following at the bottom of settings.py, after the Google block:
# locallibrary_config/settings.py
if env.bool('CANVAS_ENABLED', default=False):
SOCIALACCOUNT_PROVIDERS['openid_connect'] = {
'APPS': [
{
'provider_id': 'canvas',
'name': 'JMU Canvas',
'client_id': env.str('CANVAS_CLIENT_ID'),
'secret': env.str('CANVAS_CLIENT_SECRET'),
'settings': {
'server_url': 'https://canvas.jmu.edu',
'scope': ['openid'],
'fetch_userinfo': True,
'uid_field': 'id',
'openid_configuration_overrides': {
'userinfo_endpoint': 'https://canvas.jmu.edu/api/v1/users/self',
},
},
},
],
}
if env.bool('CANVAS_ENABLED', default=False):keeps Canvas off unless.envturns it on. Without it, allauth would show a Canvas button that can only fail. Andenv.str('CANVAS_CLIENT_ID'), with no default, would stop your site from starting at all.provider_idnames this OIDC server among any others you might add. It’s part of the redirect URI:/accounts/oidc/canvas/login/callback/.server_urlis where allauth finds the discovery document. It adds/.well-known/openid-configurationitself.scopereplaces allauth’s default for OIDC,openid profile email, with the only scope Canvas supports.openid_configuration_overridesis merged over the discovery document, so allauth sees auserinfo_endpointthat Canvas doesn’t list.fetch_userinfomakes allauth call that endpoint with the user’s new Canvas access token.uid_fieldsays which field of its answer identifies the user: Canvas’s numeric userid.
Turn it on
Send your professor the redirect URIs you’ll use, such as http://127.0.0.1:8000/accounts/oidc/canvas/login/callback/, and your deployed site’s https:// version. Canvas only sends people back to redirect URIs registered on the developer key. When you get the client ID and secret back, put them in .env and switch Canvas on:
# .env
CANVAS_ENABLED=True
CANVAS_CLIENT_ID=10000000000123
CANVAS_CLIENT_SECRET=...
Restart the server, and the login page shows JMU Canvas. Click it, and log in to Canvas if you aren’t already. Canvas asks whether to allow your site access, and sends you back.
Canvas doesn’t share email addresses through this endpoint, so the first time, allauth can’t create your account on its own. Instead, it shows a sign-up form for the rest: your email address and a username. Your first and last name come from Canvas, and are saved without asking. Your email address then gets a confirmation email, like any other new account.
Your own fields on the user
Sooner or later your project needs more about a user than Django’s User has: a display name, a bio, a favorite genre, a team. Django’s documentation lists several ways to extend the user model. Replacing User with a custom user model is the most flexible, but switching to one in a project that already has users and migrations is painful: Django’s documentation warns that it needs manual database changes. In an existing project, the usual answer is a model of your own with a one-to-one link to User, often called a profile.
Here’s one way to do it, in an app of its own. Don’t call it accounts: the Django Ninja Tutorial already has an app with that name.
uv run python manage.py startapp profiles
Add 'profiles' to the end of INSTALLED_APPS. Then write the model:
# profiles/models.py
from django.conf import settings
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, related_name="profile", on_delete=models.CASCADE
)
display_name = models.CharField(max_length=50, blank=True)
bio = models.TextField(blank=True)
def __str__(self):
return self.display_name or self.user.get_username()
OneToOneFieldis aForeignKeywithunique=True: each user has at most one profile.related_name="profile"makes it available asuser.profile.settings.AUTH_USER_MODELrefers to the user model without importing it, as the chat app’sMessage.authordoes.- Deleting a user deletes their profile (
CASCADE).
Every user should have a profile, however they were created: by signing up, through Google or Canvas, in the admin, or with createsuperuser. A post_save signal on the user model runs every time a user is saved, whichever code saved it:
# profiles/signals.py
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
A signal receiver only runs once its module has been imported. Import it in your app config’s ready() method, which Django calls at startup:
# profiles/apps.py
from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = "profiles"
def ready(self):
from . import signals # noqa: F401
To edit profiles together with their users in the admin, as Django’s documentation does, show the profile inline on the user’s admin page:
# profiles/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Profile
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
class UserAdmin(BaseUserAdmin):
inlines = [ProfileInline]
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
Create the table:
uv run python manage.py makemigrations profiles
uv run python manage.py migrate
The signal only creates profiles for users created from now on. Create the missing ones for your existing users in the shell:
$ uv run python manage.py shell
>>> from profiles.models import Profile
>>> for user in User.objects.filter(profile__isnull=True):
... Profile.objects.create(user=user)
...
Ask for it at sign-up
allauth can add fields of your own to its sign-up form. ACCOUNT_SIGNUP_FORM_CLASS names a form whose fields are added to allauth’s. After allauth creates the user, it calls the form’s signup() method:
# profiles/forms.py
from django import forms
class SignupForm(forms.Form):
display_name = forms.CharField(max_length=50, required=False)
def signup(self, request, user):
user.profile.display_name = self.cleaned_data["display_name"]
user.profile.save()
# locallibrary_config/settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.SignupForm'
The form from Canvas logins gets the field too. Google logins skip the sign-up form entirely, so their display name starts out empty. The profile’s __str__ falls back to the username.
The API
The Quickstart’s API
The Django Ninja Quickstart protects its API with django_auth, which uses the Django session. allauth logs people in to that same session, however they log in: password, Google or Canvas. Nothing in the API needs to change. As before, log in, at /accounts/login/ now, then open /api/docs, and Swagger UI sends your session and CSRF token.
The chat works the same way: Channels’ AuthMiddlewareStack reads the same session, so messages you post after logging in with Google get you as their author.
To let a client read and edit the current user’s profile, add a router to the profiles app, in the same style as the Quickstart’s chat/api.py:
# profiles/schemas.py
from django.contrib.auth.models import User
from ninja import ModelSchema, Schema
from .models import Profile
class ProfileOut(ModelSchema):
class Meta:
model = Profile
fields = ["display_name", "bio"]
class MeOut(ModelSchema):
profile: ProfileOut
class Meta:
model = User
fields = ["id", "username", "email"]
class ProfileIn(Schema):
display_name: str
bio: str = ""
# profiles/api.py
from ninja import Router
from .schemas import MeOut, ProfileIn, ProfileOut
router = Router(tags=["me"])
@router.get("/", response=MeOut)
def me(request):
return request.auth
@router.put("/profile", response=ProfileOut)
def update_profile(request, payload: ProfileIn):
profile = request.auth.profile
profile.display_name = payload.display_name
profile.bio = payload.bio
profile.save()
return profile
# locallibrary_config/api.py
from ninja import NinjaAPI
from ninja.security import django_auth
from chat.api import router as rooms_router
from profiles.api import router as me_router
api = NinjaAPI(auth=django_auth)
api.add_router("/rooms", rooms_router)
api.add_router("/me", me_router)
The API’s auth=django_auth applies to the router, so both endpoints require login, and request.auth is the logged-in User. GET /api/me/ returns the user with their profile nested inside:
{
"id": 1,
"username": "alice",
"email": "alice@example.com",
"profile": {"display_name": "Alice M", "bio": ""}
}
TaskFlow
TaskFlow, from the Django Ninja Tutorial, uses bearer tokens, and POST /taskflow/api/auth/token checks a username and password with Django’s authenticate(). That goes through AUTHENTICATION_BACKENDS, so it now uses allauth’s backend, and it keeps working: users can even get a token with their email address in place of their username. Part 7’s tests still pass.
Two things are different now:
-
Users who signed up with Google or Canvas have no password, so
/auth/tokencan’t give them a token. They can log in to the site, though. Let a logged-in session trade itself for a TaskFlow token pair, with an endpoint on the Quickstart’s session-protected API:# locallibrary_config/api.py from accounts.schemas import TokenOut from accounts.tokens import create_token_pair @api.post("/taskflow-token", response=TokenOut) def taskflow_token(request): """Trade your login session for a TaskFlow token pair.""" return create_token_pair(request.auth.id)It goes on the Quickstart’s API instead of TaskFlow’s because it needs
django_auth, and Swagger UI only sends the CSRF token on APIs that use it. Log in with Google, open/api/docs, and callPOST /api/taskflow-token. Then paste theaccesstoken into Authorize on/taskflow/api/docs. -
POST /taskflow/api/auth/signupgoes around allauth. It creates a user with no email address, so that user can get tokens but can’t log in to the site until you give them a verified email address in the admin. For your project, let people sign up through allauth’s pages, and remove the endpoint if you don’t need it. If your project’s client is a single-page app or a mobile app that can’t use allauth’s HTML pages, look at allauth’s headless mode, which offers sign-up, login and social login as a JSON API.
Templates, last
Since Prep 06, your templates/allauth/layouts/base.html puts every allauth page inside your base_generic.html, with your sidebar. The forms themselves are still plain, unstyled HTML. You can change that too: every allauth page, form element and email is a template that you can override in your own templates/ folder, the same way. See Templates in allauth’s documentation.
How the login page looks is about the least interesting part of your course project. Nobody grades your project on how nice the sign-up form is, and every hour spent restyling allauth’s pages is an hour not spent on the features that make your project yours. Get everything else working first. If there’s time left at the very end, then restyle them.
What you have now
- Sign-up with a username, email and password, with email verification, and login with either the username or the email address (from Prep 06)
- Login with Google, configured from
.env - Login with JMU Canvas, ready to switch on as soon as you have a client ID and secret
- A
Profilefor every user, filled in at sign-up, and editable throughGET /api/me/andPUT /api/me/profile - APIs that work for every user, however they log in
Commit your work. Check git status first: .env must not be in it, but .env.example should be.