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:
Using Email as Username
To use email as the username, you can either:
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!