Django Email Login (instead of using username)
--
by default, django use username to login. For some case, using email is better than username (most user remember email rather than username). Important: email need to be unique to support this login mechanism.
Step 1: Preparation, Create Django Project
create virtualenv: virtualenv venv
start virtualenv: venv/Scripts/activate
install Django in virtualenv: pip install django==4.2
Create Django: django-admin startproject myproject
Go to myproject folder: cd myproject
Step 2: Create Django Apps
Create apps: python manage.py startapp core
Step 3: Create User Models (core/models.py) extends AbstractUser
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
email = models.EmailField(unique=True)
email field should be set as unique field
Step 4: Create Backend Authentication (core/backends.py)
Create new file core/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
Step 5: Update myproject/settings.py
Add INSTALED_APPS, add AUTH_USER_MODEL and add AUTHENTICATION_BACKENDS
...
INSTALLED_APPS = [
...
'core', #updated
]
...
AUTH_USER_MODEL = 'core.User' #updated
AUTHENTICATION_BACKENDS = ['core.backends.EmailBackend'] #updated
Step 6: Register User Model in Admin Site
from django.contrib import admin
from .models import User
# Register your models here.
admin.site.register(User)
Step 7: Makemigration and Migrate
Make migrations: python manage.py makemigrations
Migrate: python manage.py migrate
Step 8: Create Superuser
Make migrations: python manage.py createsuperuser
Type username, email password and retype password
Step 9: Test
Run Server: python manage.py runserver
Testing: http://127.0.0.1:8000/admin