Django - Create user profile on user creation

こ雲淡風輕ζ 提交于 2019-11-28 09:42:33
Limaaf

Just figured it out.

I forgot to add null=True to the rest of UserProfile model fields.

So the accounts.models.UserProfile fields now looks like:

user = models.ForeignKey(User, unique=True)
birth_date = models.DateField(null=True)
genre = models.CharField(max_length=1, choices=GENRE_CHOICES, null=True)
address = models.CharField(max_length=150, null=True)
postal_code_4 = models.PositiveIntegerField(null=True)
postal_code_3 = models.PositiveIntegerField(null=True)
locatity = models.CharField(max_length=30, null=True)
marital_status = models.CharField(max_length=1, choices=MARITAL_STATUS_CHOICES, null=True)
child_amount = models.PositiveSmallIntegerField(null=True)
is_merchant = models.BooleanField(default=False)
store = models.ForeignKey(Store, null=True)

...and everything is working as intended!

Cheers for trying to help Ashray ^^

You shouldn't use:

user = models.ForeignKey(User, unique=True)

Instead use this:

from django.conf import settings
..
user = models.OneToOneField(settings.AUTH_USER_MODEL)
user9457455
def create_profile(sender,**kwargs ):
    if kwargs['created']:
        user_profile=UserProfile.objects.create(user=kwargs['instance'])


post_save.connect(create_profile,sender=User)

I think this will help you.

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if kwargs.get('created', True) and not kwargs.get('raw', False):
            Profile.objects.create(user=instance)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!