Populate Custom User Attributes When Signing Up Using Django Allauth
Learn how to set custom attributes to your User model when signing up users with Django Allauth.
Published: 21 Mar, 2024
Django Allauth provides a plug-and-play authentication system with minimal configuration required.
However, you’ll often require users to supply specific information not in the default User model while signing up.
In this post, I’ll show you how to customize the allauth signup form and flow to store a field containing the user’s company name.
Create a customer user model
First, you’ll add the field to your custom user model.
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
company_name = models.CharField(max_length=150)
After that, you’ll tell Django to use this model instead of the default one in your settings.py file.
...
AUTH_USER_MODEL = 'my_app.User'
...
Customize the signup process
You’ll create a new sign up form inheriting from the one that allauth provides.
from django import forms
from allauth.account.forms import SignupForm as AllauthSignupForm
class SignupForm(AllauthSignupForm):
company_name = forms.CharField(max_length=150)
Then, you’ll create an adapter to use the new field you added to the form.
from allauth.account.adapter import DefaultAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def save_user(self, request, user, form, commit=True):
user = super().save_user(request, user, form, False)
user.company_name = form.cleaned_data['company_name']
if commit:
user.save()
return user
Now, you’ll tell allauth to use the new form on the signup page.
ACCOUNT_FORMS = {
"signup": "my_app.forms.SignupForm"
}
You’ll also tell it to use your new adapter by adding the following in settings.py
ACCOUNT_ADAPTER = 'myapp.adapters.AccountAdapter'
Try signing up now and you’ll see the form asking for a company name. After signup up, you’ll see the new user object contains the company name you entered during the process.
Summary
As you can see, allauth isn’t only easy to integrate but also easy to customize.
To customize signup, all you need to do is to create a custom signup form, adapter, and then configure allauth to use them in settings.py.