Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Custom User in Django

custom user in Django

4 min readOct 25, 2023

--

Press enter or click to view image in full size

👉If you are not a medium member here is a link for you

Hi everyone, I hope everything is going well with you. Today, I’m writing a new blog post about Custom Users in Django. I’ve already wrote a blog post on this subject, but I’m approaching it differently this time.

The high-level Python web framework Django comes with a reliable authentication mechanism built right in. But occasionally, you might need to develop unique user models that go beyond what Django’s default User model can offer. This can be necessary for extra user attributes, unique user authentication techniques, or other particular needs. This blog post will explain and provide examples for creating custom users in Django using the AbstractUser and UserManager classes.

👉Why Customize the User Model?

There are various reasons to customize the User model in Django:

  1. Additional Fields: You might need to store additional information about your users, such as a user profile image, phone number, or user type.
  2. Authentication Methods: You may want to use custom authentication methods, such as email or phone number, in addition to or instead of the default username and password.
  3. User Permissions: Custom user models can define specific permissions for different user roles within your application.
  4. Integration with Third-Party Apps: Some third-party packages and apps require a custom user model to work correctly.

👉Using AbstractUser and UserManager

To create a custom user model in Django, you can start with the AbstractUser class and create a custom manager using UserManager. The AbstractUser class contains the basic fields and methods of the User model, allowing you to extend it according to your requirements.

Here’s a step-by-step guide with examples:

Step 1: Create a New Django Project

If you haven’t already created a Django project, you can do so using the following command:

django-admin startproject customuserproject

Step 2: Create a Custom User Model

In your Django project, open the models.py file in the app where you want to define your custom user model. Define a class that extends AbstractUser:

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

class CustomUserManager(BaseUserManager):
def create_user(self, username, email, password=None, **extra_fields):
if not email:
raise ValueError("The Email field must be set")
email = self.normalize_email(email)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)

if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")

return self.create_user(username, email, password, **extra_fields)

class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
date_of_birth = models.DateField(null=True, blank=True)

# Add your custom fields here

objects = CustomUserManager()

In the code above:

  • We define a CustomUserManager class that inherits from BaseUserManager. This custom manager is responsible for creating users and superusers.
  • We create the CustomUser class, extending AbstractUser. We add custom fields like email, first_name, last_name, and date_of_birth.

Step 3: Configure the Custom User Model

In your project’s settings (settings.py), specify your custom user model by setting the AUTH_USER_MODEL variable:

AUTH_USER_MODEL = 'yourapp.CustomUser'

Replace 'yourapp' with the actual name of the app containing your custom user model.

Step 4: Create and Apply Migrations

Generate the necessary migrations for your custom user model and apply them to the database using the following commands:

python manage.py makemigrations
python manage.py migrate

Step 5: Using the Custom User Model

You can now use your custom user model for authentication, user creation, and other operations. For example:

👉Creating a new user:

from yourapp.models import CustomUser

user = CustomUser.objects.create_user(username='myusername', email='user@email.com', password='mypassword')

👉Creating a superuser:

superuser = CustomUser.objects.create_superuser(username='adminuser', email='admin@admin.com', password='adminpassword')

👉Conclusion

Customizing the user model in Django is a powerful feature that allows you to tailor your application’s authentication system to your specific needs. By using the AbstractUser and UserManager classes, you can extend the User model to include additional fields, custom methods, and other functionality. This flexibility makes Django a great choice for a wide range of web applications.

Thank you 🤘

💬 Leave a response to this article by providing your insights, comments, or requests for future articles.

Get Gajanan Rajput💚’s stories in your inbox

Join Medium for free to get updates from this writer.

📲 Share the articles with your friends and colleagues on social media.

➕ Follow me on Medium and check other articles.

Thanks for following and claps 😋

Let’s Get in Touch! Follow me on:

>Instagram: @rajput_gajanan_07.

>GitHub: @gajanan0707

>Linkedin: Gajanan Rajput

>Website for more blogs: https://mrcoder701.com/

Press enter or click to view image in full size
https://www.buymeacoffee.com/gajanan0707
https://www.buymeacoffee.com/gajanan0707

In Plain English

Thank you for being a part of our community! Before you go:

--

--

Gajanan Rajput💚
Gajanan Rajput💚

Written by Gajanan Rajput💚⁠

Full-Stack Dev | Tech Writer | Storyteller Sharing | coding tips, and heartfelt stories. tech insights and inspiration | Writing since Oct 8, 2021 ✍️

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.