How to Implement Custom User Model in Django

Setp by step guide to set a custom user model for a new Django project.
August 9, 2024 by
How to Implement Custom User Model in Django
Hamed Mohammadi
| No comments yet

Customizing user authentication and management is crucial for building tailored Django applications. This guide will walk you through the process of creating a custom user model from scratch, providing a solid foundation for your project and allowing you to define specific user attributes and behaviors beyond the default Django user.

To ensure seamless integration and avoid potential migration conflicts, it's essential to implement a custom user model before creating any initial migrations. This strategic approach allows for complete control over user data structures from the outset. To begin, create a dedicated app, such as 'accounts', within your Django project to house the custom user model and its associated logic.:

(.venv) $ python manage.py startapp accounts

Within your newly created accounts app, navigate to the models.py file. This is where you'll define your custom user model. As shown in the example code below, you have the flexibility to modify this model throughout your project's development. Any changes to the model structure will require running migrations, following the same process you would use for any standard Django model.


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

# Create your models here.

class CustomUser(AbstractUser):
	​bio = models.TextField(default="Bio", max_length=500) # Add Min and Max Characters
	​image = models.ImageField(upload_to="profiles", null=True, blank=True)

	​can_post = models.BooleanField(default=True)
	​can_comment = models.BooleanField(default=True)
	​verified = models.BooleanField(default=False)


To integrate your custom user model into your Django project, you'll need to make adjustments to your project's settings.py file. Firstly, add your accounts app to the INSTALLED_APPS list. Secondly, specify the path to your custom user model using the AUTH_USER_MODEL setting. This tells Django to use your custom model for authentication and user management instead of the default one:

INSTALLED_APPS = [ ... "accounts.apps.AccountsConfig", ... ]
At the end of settings.py file add this line to set the custom user model:

AUTH_USER_MODEL = "accounts.CustomUser"

To manage your custom user model within the Django admin interface, open the admin.py file in your accounts app. Here, you'll define a custom subclass of UserAdmin to tailor the admin experience for your specific user model. Something like this:

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

from .forms import CustomUserCreationForm, CustomUserChangeForm

CustomUser = get_user_model()

# Register your models here.


class CustomUserAdmin(UserAdmin):
    list_display = (
        "username",
        "email",
        "first_name",
        "last_name",
        "bio",
        "image",
        "can_post",
        "can_comment",
        "verified",
    )
    list_filter = (
        "is_staff",
        "is_superuser",
        "is_active",
        "can_post",
        "can_comment",
        "verified",
    )
    search_fields = ("username", "first_name", "last_name", "email")
    fieldsets = (
        (None, {"fields": ("username", "password")}),
        ("Personal info", {"fields": ("first_name", "last_name", "email")}),
        ("Permissions", {"fields": ("is_active", "is_staff", "is_superuser")}),
        ("Important dates", {"fields": ("last_login", "date_joined")}),
        (
            "Custom fields",
            {"fields": ("bio", "image", "can_post", "can_comment", "verified")},
        ),
    )

    # Add custom methods for display or actions here if needed


admin.site.register(CustomUser, CustomUserAdmin)


For demonstration purposes, all fields of the custom user model are included in the admin interface. However, in a production environment, you might choose to restrict editing access to certain fields based on security or user roles.

With your custom user model and admin configuration in place, it's time to create the necessary database schema. Run the migrations for your accounts app to sync the changes you've made to the database:

(.venv) $ python manage.py makemigrations accounts
(.venv) $ python manage.py migrate.


How to Implement Custom User Model in Django
Hamed Mohammadi August 9, 2024
Share this post
Archive

Please visit our blog at:

https://zehabsd.com/blog

A platform for Flash Stories:

https://readflashy.com

A platform for Persian Literature Lovers:

https://sarayesokhan.com

Sign in to leave a comment