The User Model

Create and manage users with the built-in User model.

SyntaxUser.objects.create_user(username, email, password)

The default User model stores a username, password (hashed), email and flags like is_staff and is_superuser. Create users with create_user(), which hashes the password for you.

For real projects it is best practice to define a custom user model early, but the default works out of the box.

Example

Example Β· python
from django.contrib.auth.models import User

# Create a user (password is hashed automatically)
user = User.objects.create_user(
    username="ada",
    email="[email protected]",
    password="s3cret!",
)

# Check a password
user.check_password("s3cret!")   # True

When to use it

  • A developer queries the User model to find all users who signed up in the last 7 days for a weekly report.
  • A developer uses User.objects.create_user() to programmatically create accounts during a data import script.
  • A team extends the built-in User with AbstractUser to add an avatar field without breaking existing auth code.

More examples

Create a user programmatically

Uses create_user() which hashes the password automatically, unlike create() which stores it in plain text.

Example Β· python
from django.contrib.auth import get_user_model

User = get_user_model()
user = User.objects.create_user(
    username="alice",
    email="[email protected]",
    password="SecurePass1!",
)

Extend User with AbstractUser

Extends AbstractUser to add custom fields; AUTH_USER_MODEL must be set before the first migration.

Example Β· python
# accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    avatar = models.ImageField(upload_to="avatars/", null=True, blank=True)
    bio = models.TextField(blank=True)

# settings.py
AUTH_USER_MODEL = "accounts.CustomUser"

Query and update user fields

Queries users who joined in the last week using a date field lookup on the built-in User model.

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

# Find recently joined users
from django.utils import timezone
from datetime import timedelta
new_users = User.objects.filter(
    date_joined__gte=timezone.now() - timedelta(days=7)
)

Discussion

  • Be the first to comment on this lesson.
The User Model β€” Django | SoundsCode