Search code examples
djangodjango-modelsdjango-signals

Where does my django signals look for a missing argument Created in the createprofile function?


I am using django signals to create a profile after a user is created but I get this wird error telling that the create profile function is missing the created argument I even tried without a decorator but It didn't work. I don't know what I am missing.

here is the model and the signal itself.

 class Profile(models.Model):
    user = models.OneToOneField(
        User, verbose_name="user", related_name="profile", on_delete=models.CASCADE
    )
    full_name = models.CharField(max_length=150, blank=True, null=True)
    date_of_birth = models.DateField(blank=True, null=True)
    bio = models.TextField()
    location = models.CharField(max_length=100, blank=True, null=True)
    picture = models.ImageField(
        default="media/profile_pics/default.jpg", upload_to="media/profile_pics"
    )
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.user.username}'s profile"


@receiver(pre_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(pre_save, sender=User)
def create_profile(sender, instance, **kwargs):
    instance.profile.save()

And I am using django allauth for the authentication and authorization.

Here is the the error from the terminal

     File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\allauth\account\adapter.py", line 246, in save_user
    user.save()
  File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\db\models\base.py", line 750, in save_base
    pre_save.send(
  File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
    return [
  File "C:\Users\Papis\Desktop\Dev\projects\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
TypeError: create_profile() missing 1 required positional argument: 'created'
[09/Jul/2021 18:54:00] "POST /accounts/signup/ HTTP/1.1" 500 136997

Solution

  • The post_save signal would be what you are looking for here.

    @receiver(post_save, sender=User)
    def create_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)