Django / Django Authentication and Authorization

Implementing Custom User Models

In this tutorial, you'll learn how to implement custom user models in Django. This includes replacing Django's default user model with your own.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers user authentication, authorization, and managing user roles in Django.

Implementing Custom User Models in Django

Introduction

In this tutorial, we are going to learn how to implement custom user models in Django by replacing Django's default user model with our own.

By the end of this tutorial, you will know how to:
1. Create a custom user model
2. Replace Django's default user model with your own custom model

Prerequisites:
- Basic knowledge of Python
- A working understanding of Django

Step-by-Step Guide

Django's built-in User model is quite robust, but there may be instances where you want to implement custom behavior. Fortunately, Django allows us to extend or completely replace the built-in User model.

Creating a Custom User Model

Let's start by creating a new application named users. In your terminal, type:

python manage.py startapp users

In the users/models.py file, we'll create our custom user model.

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

class CustomUser(AbstractUser):
    # Add additional fields in here
    about = models.TextField(blank=True)

This CustomUser model will have all the fields of the built-in User model and an additional field about.

Replacing Django's Default User Model

To replace Django's default user model, we need to update the AUTH_USER_MODEL setting in our settings file (settings.py).

AUTH_USER_MODEL = 'users.CustomUser'

This tells Django to use our CustomUser model instead of the built-in User model.

Code Examples

  1. Adding more complex fields to the custom user model:
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    # Add more complex fields
    about = models.TextField(blank=True)
    birthdate = models.DateField(null=True, blank=True)

In this example, we have added a birthdate field to our CustomUser model. This field is optional (null=True, blank=True).

  1. Changing the string representation of the model:
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    about = models.TextField(blank=True)

    def __str__(self):
        return self.email

In this example, we have overridden the __str__() method to return the user's email instead of their username.

Summary

In this tutorial, you've learned how to create a custom user model and replace Django's default user model. To continue learning, you could explore adding more complex fields to your user model, or how to customize the user model's admin interface.

Practice Exercises

  1. Add a phone_number field to the CustomUser model. This field should be unique and optional.
  2. Override the get_full_name() method of the CustomUser model to return the user's email.

Solutions:
1. Adding a phone_number field:

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

class CustomUser(AbstractUser):
    about = models.TextField(blank=True)
    phone_number = models.CharField(max_length=20, unique=True, null=True, blank=True)
  1. Overriding the get_full_name() method:
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    about = models.TextField(blank=True)

    def get_full_name(self):
        return self.email

In this solution, the get_full_name() method returns the user's email instead of their full name.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help