Django Custom Authentication

ยท

2 min read

Table of contents

No heading

No headings in the article.

By default Django is restricted to only using username and password for authentication. But with the use of custom authentication, Django allows user to be able to use any field with the authentication . The basic purpose of custom authentication is to allow user to be able to use another field apart from username to authenticate. While another company may use email for authentication, other company might decide to use unique id for authentication.

I created a custom authentication for this article by using email and password for the authentication. After creating a django environment, in settings.py file we have to register the app in the list of installed apps

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "accounts"
]

Screenshot (97).png

In the models.py file for the accounts app, we have to write the user model.

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

class User(AbstractUser):
    email = models.EmailField(unique=True, Verbose_name="Email Address")

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username"]

From the code above, i imported the AbstractUser The AbstractUser is use for full control over the user model. It implements a fully featured user model. I also have to call the EmailField and i added unique=True because by default email is not unique in django and we don't want to allow the main authentication field not to be unique.

USERNAME_FIELD = "email" allows django to know that the field we want as username is the email and REQUIRED_FIELDS = ['username"] tells django to allow username to be the required field.

Screenshot (99).png

Also make sure you add

AUTH_USER_MODEL  = "accounts.User"

It tells Django we are no longer using the normal authentication, instead we are using the authentication we created.

Screenshot (100).png

Note: The format for the accounts.User is the app name.the model field we created.

The next thing is to register the User model in the admin.py file

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth import get_user_model

class UserAdmin(BaseUserAdmin):
    add_fieldsets = (
      (
            None, {
                            "classes": ("wide"),
                            "fields": ("email", "username", "password1", "password2")
                        }
      )
)

admin.site.register(get_user_model(), UserAdmin)

Screenshot (101).png

Finally make migration and migrate. Also create superuser to check the custom authenticaiton

  python manage.py makemigrations
  python manage.py migrate
  python manage.py createsuperuser

Github Link

Happy learning ๐ŸŽ‰ ๐ŸŽ‰ ๐ŸŽ‰

ย