0

I have a model called 'User profiles' that is a custom user, it takes a user in a OneToOneField and also has additional fields like 'age', 'is_teacher', 'is_location'.

My Problem is that when I create a normal user, this 'User Profiles' dosen't create a new User. How do I make that happen?

I know that I have to do something like this with a receiver (Where do I add the receiver?):

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
if created:
    # Create your user data
    pass

These are my models:

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

class UserProfile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  age = models.IntegerField(default=18)
  description = models.CharField(max_length=300)
  is_student = models.BooleanField(default=False)
  is_teacher = models.BooleanField(default=False)

  def __str__(self):
    return self.user.username
William Abrahamsson
  • 229
  • 1
  • 6
  • 19

1 Answers1

0

So you're almost there!

a signal is function that executes after something happens, in the case a User model gets saved to the database, it in turn calls every function that's decorated with @receiver and that model as a sender it can find.

What you need to do is check if its a new or updated user, and if its a new one you create the users profile. Something like:

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
    if created:
        user  = instance
        profile = UserProfile.objects.create(user=user, age=12)

Now, this only works if the User itself contains enough information to create the profile!

krs
  • 4,096
  • 19
  • 22
  • How do I make this work with terminal: createsuperuser? – William Abrahamsson May 31 '19 at 15:07
  • @WilliamAbrahamsson May be add those fields in your custom user and add it in REQUIRED_FIELDS https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS – Prakash S Jul 13 '19 at 08:17