Django - User And User Profile Form Creating Two Profiles Instead Of One
Solution 1:
You should get rid of those signals. They are doing nothing useful, and are probably the cause of the duplication.
Instead, you need to do something to tell the form that the profile you are creating belongs to the user you just created:
user= form.save()
profile = profileform.save(commit=False)
profile.user =user
profile.save()
You should also get rid of the save methods on both the form and the model - there's no point in defining an overridden method whose sole action is to call the super method.
Similarly, you can get rid of the checks for user is not None
and user.is_active
; you know the user exists and is active, because you just created it.
Solution 2:
In practice, imo, better always have profile for each user. To achieve this post/pre-save signals that you use make sense. For example when user just registered in system, Profile for new user will be autocreated Code will be very simple:
classProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# your fields
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
Also, if you already have pool of users without profiles, and want to create profiles for them you can use data-migration, if you need code for such data migration, please see post in my blog.
Post a Comment for "Django - User And User Profile Form Creating Two Profiles Instead Of One"