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:
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.
Uniqueness: Email addresses are generally unique for each user, reducing the likelihood of username collisions.
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
This code creates a newfrom django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True)
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.