David Thao
David Thao

Reputation: 9

How to automatically create new Profile once a new User is created in Django?

Currently running into this issue with my Django app that I am working on.

I have a model class Profile that I want to be automatically created and assigned to a new user. Was wondering how I can do this? I do have a custom user model that I have set up as well.

class Profile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)

Upvotes: 0

Views: 551

Answers (1)

Ajay Lingayat
Ajay Lingayat

Reputation: 1673

You can try by creating a signal:

This executes after saving a record of User model as post_save signal is used.

from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
       if created:
          Profile.objects.create(user=instance).save()
    except Exception as err:
       print(f'Error creating user profile!\n{err}')

Here instance is the user object, sender is the User model & created is a boolean object used to check is a new record is created after saving the User model on not.

You can get more information about it over here.

Upvotes: 2

Related Questions