Django Tutorial: User Model 🎯

beginner
19 min

Django Tutorial: User Model 🎯

Welcome to our comprehensive guide on Django's User Model! In this lesson, we'll delve into creating, managing, and customizing user accounts in Django applications. Let's get started!

What is the User Model? πŸ“

The User Model is a built-in Django model that manages authentication and user permissions. It's pre-installed when you create a new Django project.

Why use the User Model? πŸ’‘

The User Model handles authentication out-of-the-box, saving you time and effort. It provides essential functionalities like user registration, login, password reset, and more.

Creating a New User βœ…

To create a new user, you can use Django's built-in management commands.

bash
$ python manage.py createsuperuser

You'll be asked to enter the username, email, and password for the new superuser.

User Model Structure πŸ“

The User Model is located in django.contrib.auth.models. Some of its fields include:

  • username: a unique username for the user
  • email: a unique email address for the user
  • password: encrypted user password
  • is_active, is_staff, is_superuser: flags for user permissions

Accessing the User Model πŸ’‘

To access the User Model in your views, you can use the get_user_model() function:

python
from django.contrib.auth import get_user_model User = get_user_model()

Customizing the User Model πŸ’‘

Django allows you to customize the User Model to suit your application's needs. To do this, you'll create a new model that inherits from the base AbstractBaseUser and PermissionsMixin classes:

python
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class CustomUserManager(BaseUserManager): pass class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # Add other custom fields as needed # Default Manager for the CustomUser model objects = CustomUserManager() # Override the built-in methods def get_full_name(self): return f"{self.first_name} {self.last_name}" def get_short_name(self): return self.first_name

After creating the custom User Model, you'll need to update the AUTH_USER_MODEL setting in your Django project's settings.py file:

python
AUTH_USER_MODEL = 'app_name.CustomUser'
Quick Quiz
Question 1 of 1

What does the User Model handle in Django applications?

This is just a taste of what Django's User Model has to offer. In the next sections, we'll dive deeper into customizing the User Model and managing user accounts in your Django applications. Stay tuned! πŸš€