Adding Extra Fields to the Django User Model Using a One-to-One Relationship

In the ready-made model structure that comes in the Django Framework, if new fields are needed in the User model, we can solve it in two ways.

One of them is extending the AbstractBaseUser model.

The second is to create a new model and connect it to the User model with a one-to-one relationship.

In this article, I will explain how we can provide extra fields to the User model using the second way.

Extra fields that we will need in the User model will be defined in the Profile model. In our Profile model, user’s information such as phone, address, picture will be kept. When each user is created in the database, a row with one-to-one relationship to the User model must be created in the Profile model.

For this, we define a function named user_is_created() in the model.py file included in our models.

We will use the post_save signal to detect if there is a create action that will occur in the user table.

We will do this by using the @receiver decorator on top of our user_is_created () function.

from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save # Produce a signal if there is any database action.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete= models.CASCADE )
    occupation = models.CharField(max_length=150, null=True, blank=True)
    phone = models.CharField(max_length=30, null=True, blank=True)
    address = models.CharField(max_length=250, null=True, blank=True)
    city = models.CharField(max_length=150, null=True, blank=True)
    country = models.CharField(max_length=150, null=True, blank=True)
    image = models.ImageField(upload_to='pictures/%Y/%m/%d/' , max_length=255, null=True, blank=True)

    def __str__(self):
        return "{0}".format(self.user.email)

# When any User instance created, Profile object instance is created automatically linked by User 
@receiver(post_save, sender = User)
def user_is_created(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user= instance)
    else:
        instance.profile.save()
Topluluk Tarafından Doğrulandı simgesi

DJANGO VERSİYON : 3.1.1

Topluluk Tarafından Doğrulandı simgesi