Home >Backend Development >Python Tutorial >How to Best Extend the Django User Model with Custom Fields?

How to Best Extend the Django User Model with Custom Fields?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 13:29:14265browse

How to Best Extend the Django User Model with Custom Fields?

Extending the Django User Model: Optimal Approaches

When extending the built-in Django User model with custom fields, two main approaches stand out:

1. Using a OneToOneField(User) Property

This is the recommended Django approach and involves creating a new model with a one-to-one relationship with the User model. This "profile" model can store additional information about the user.

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

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Custom fields here, e.g.:
    address = models.CharField(max_length=255)
    phone_number = models.CharField(max_length=15)
    # ...

2. Substituting with a Custom User Model

This approach involves replacing the Django User model entirely with a custom one that includes the desired modifications. However, it is considered drastic and comes with warnings:

  • It can break other Django functionality that relies on the User model.
  • It involves copying and altering the Django auth module.
  • It may require re-implementing authentication mechanisms.

Using Email as Username

To use email as the username, you can either:

  • Override the get_username() method in your custom User model.
  • Utilize the set_username() method to update the username of an existing user.

Example:

class CustomUser(AbstractUser):

    def get_username(self):
        return self.email

# ...
user = CustomUser.objects.get(username='john@example.com')
user.set_username('jack@example.com')
user.save()

The above is the detailed content of How to Best Extend the Django User Model with Custom Fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn