Sobes.tech
Junior — Middle

What methods can be used to implement a user model in Django?

sobes.tech AI

Answer from AI

In Django, the user model can be implemented in several ways:

  1. Use the built-in User model from django.contrib.auth — the simplest option, suitable for most cases.

  2. Extend the built-in User model via a user profile (OneToOneField) — create a separate model with additional fields linked to User:

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

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()
  1. Create a custom user model inheriting from AbstractUser or AbstractBaseUser:
  • Inheriting from AbstractUser allows adding fields to the standard user model.

  • Inheriting from AbstractBaseUser gives full control over the model but requires implementing all necessary methods.

Example of a custom model based on AbstractUser:

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

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

When using a custom model, it must be specified in the settings:

AUTH_USER_MODEL = 'myapp.CustomUser'

The choice of method depends on the project requirements and the need to extend user functionality.