Table of contents
1.
Introduction
1.1.
Extending Signup Form in django allauth
2.
User Intervention and Custom Validations
2.1.
Restrict list of emails
2.1.1.
Add a maximum Length to a username.
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

Extending and Customizing django-allauth

Author Naman Kukreja
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

When you have made your signup forms, you cannot do much about it if you want to edit it, as you have to make a completely different form again.

But here, django-allauth gives you another edge over other apps in Django that you can customize your signup form according to your preferences.

Now without wasting any time further, let's dive into our topic and move to add validations and custom processes.

Extending Signup Form in django allauth

The question that revolves around most of the programmers who are learning django-allauth first time is how to add custom fields or additional fields to the signup form. 

From allauth.account.forms you can extend the SignupForm class. You just have to create a custom class, pass the signupForm, and save it after defining custom fields.

The user object will be passed to other modules for validation, so we have to return the user object. You need to include a variable in settings.py

from allauth.account.forms import SignupForm
from django import forms

class CustomSignupForm(SignupForm):
    first_name = forms.CharField(max_length=25, label='First Name')
    last_name = forms.CharField(max_length=25, label='Last Name')

    def save(self, request):
        user = super(CustomSignupForm, self).save(request)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        return user


Here CustomSignupForm is the extended class as it has all the features of the SignupForm class and some necessary features.

Here custom fields by the name last_name and first_name are created and saved.

In settings.py, the ACCOUNT_FORMS is,

ACCOUNT_FORMS = {
'signup': 'YourProject.forms.CustomSignupForm',
}


You can extend any other created custom form in ACCOUNT_FORMS.

Similarly, UserForm, AddEmailForm,  LoginForm, and others can be extended. One common mistake that programmers make while extending these forms and linking them in settings.py is they forgot to pass the original form as a parameter. This sometimes creates problems as one might have to return users or handle custom validations.

User Intervention and Custom Validations

Here, we will discuss how to intervene in user registration flow and add custom validation.

Most of the customization problems you will face while using django-allauth can be solved by using DefaultAccountAdapter.

Restrict list of emails

After figuring out a way to fetch and store the restricted list, you can raise the validation errors in the registration form by using adapters when a restricted email tries to register.

Override the clean_email method and extend and extend DefaultAccountAdapter. Extend the default adapter class and create adapter.py in your project directory.

from allauth.account.adapter import DefaultAccountAdapter
from django.forms import ValidationError

class RestrictEmailAdapter(DefaultAccountAdapter):
    def clean_email(self, email):
        RestrictedList = ['Here goes the restricted list.']
        if email in RestrictedList
            raise ValidationError('YOu are not allowed to register.\
                                                Please contact admin.')
        return email

To your extended class, point the account adapter in settings.py.

ACCOUNT_ADAPTER='YourProject.adapter.RestrictEmailAdapter'

Add a maximum Length to a username.

We cannot use ACCOUNT_USERNAME_MAX_LENGTH as it doesn't exist in the allauth library.

Instead, we have to use DefaultAccountAdapter to use this without much pain. Override the clean_username method and extend the DefaultAccountAdapter class.

After custom validation, you need to reference the clean_username once again to complete other inbuilt validations.

The reference line in the previous paragraph is very important to work with DefaultAccountAdapter. For the module to complete validations, you should always reference the original module name.

from allauth.account.adapter import DefaultAccountAdapter
from django.forms import ValidationError

class UsernameMaxAdapter(DefaultAccountAdapter):
    def clean_username(self, username):
        if len(username) > 'Your Max Size':
            raise ValidationError('Please enter a username \
                                    smaller than the current one')
       
        # For other default validations.
        return DefaultAccountAdapter.clean_username(self, username)


Finally, In settings.py point to the subclass.

ACCOUNT_ADAPTER = 'YourProject.adapter.UsernameMaxAdapter'


The modules such as clean_password, populate_username can flow without rewriting them and have a custom process.

DefaultAccountAdapter is a handy tool for intervening in allauth's default process.

Frequently Asked Questions

  1. What are migrations in Django?
    These are the files saved in the migration directory and created when you run the makemigrations command.
     
  2. What are the commands used to create a project in Django?
    Project, manage.py, _init_.py are the commands for creating a project in Django.
     
  3. Can we intervene in user registration in Django?
    Yes, we can intervene in user registration in Django.
     
  4. Can we add custom fields in the signup Form?
    Yes, we can add custom fields in the signup form.

Key Takeaways

Here, we have learned how to add custom fields in the signup form, intervene in user registration, other validation.

If you want to know how to set up and configure django-allauth, you should refer to this article to give you a complete idea about the same.

Live masterclass