Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

Django Authentication using an Email Address

4 min read


Authentication is a crucial aspect of any web application, ensuring that only authorized users can access specific resources and perform actions. Django, a powerful web framework for Python, provides robust authentication mechanisms out of the box.

Django's built-in User model uses a username as the primary means of identifying a user. However, you may want to use an email for authentication for your web application.

In this article, we will show you how to configure Django to use an email address as the primary means of identifying a user when they log in.

Considering the scope of the article I am assuming you already have a basic Django project up and running if not reading the following articles is recommended.

Why Use Email Address for Authentication?

Traditionally, many web applications use usernames for authentication, but email addresses offer several advantages:

  1. User-Friendly: Users are more likely to remember their email addresses compared to usernames, especially if they use the same email address across multiple platforms.

  2. Uniqueness: Email addresses are generally unique for each user, reducing the likelihood of username collisions.

  3. Simplification: Users don't need to remember yet another username, making the authentication process more straightforward.

Enable Login with Email in Django

First you need to create a custom User model that uses an email field instead of a username field.

To do this, create a new file called models.py in your users app's directory and add the following code:

users/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
This code creates a new CustomUser model that inherits from Django's built-in AbstractUser model. The new model has an additional email field that is set to be unique.

Next, you will need to update your project's settings file to use your custom User model.

Open the settings.py file and add the following code:

AUTH_USER_MODEL = 'users.CustomUser'

This line tells Django to use your custom User model when it needs to work with users.

At this point we can run the migrations, 

python manage.py makemigrations
python manage.py migrate

Create a custom authentication backend

Django uses authentication backends to authenticate users. By default, it uses a backend that looks up users by their username.

To use an email address instead, you will need to create a custom authentication backend. To do this, create a new file called backends.py in your users's directory and add the following code:

users/backends.py

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

This code creates a new EmailBackend class that inherits from Django's built-in ModelBackend class. The authenticate() method looks up a user by their email address instead of their username.

Finally, you will need to update your project's settings file to use your custom authentication backend.

Update Settings

Open the settings.py file and add the following code:

AUTHENTICATION_BACKENDS = ['users.backends.EmailBackend']

This code tells Django to use your new custom authentication backend. 

Test it out!

Once you've made these changes, you should be able to log in with email and password in the Django admin. To test it, you just need to create a superuser with an email and password and then login in into the admin dashboard.

Forms and Views 

Update the login and registration forms to ask for email instead of username. You can do this by creating custom forms that inherit from the built-in Django forms and include an email field instead of a username field.

Creating custom authentication forms 

from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm

class CustomAuthenticationForm(AuthenticationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'autofocus': True}))

class CustomUserCreationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    class Meta:
        model = CustomUser
        fields = ('email', 'password1', 'password2')

Then, update the views and templates to use the new forms and authentication backend. 

Conclusion

In this article, we explored how to enable Django authentication using an email address instead of a username. By doing so, we make the authentication process more user-friendly, leveraging the unique nature of email addresses to simplify the user experience.

Django's flexibility allows us to customize authentication to suit the needs of our web applications. Using an email address for authentication is a modern approach that enhances security and user convenience.

Remember that security is paramount, and you should always use secure password storage mechanisms, such as bcrypt, and consider adding additional authentication factors like Two-Factor Authentication (2FA) for increased security.

With email-based authentication in place, your Django application is ready to offer a seamless and user-friendly authentication experience.


DJANGO

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read