cpit
cpit

Reputation: 155

Extending the Django User Model OneToOne - User profile not saving

I am trying to build an application that allows users to register and meet other users with similar interests. I am extending the user model using a OneToOne field but I run into a problem when I try to register some users: The profile does not save. The user data saves, but the profile data does not.

I do not understand what I am doing wrong, as I followed a tutorial to write the program.

This is my Models.py file:

class Profile(models.Model):
    GENDERS = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    email = models.EmailField(max_length=254, blank=True)
    gender = models.CharField(choices=GENDERS, max_length=1, null=True, default='')
    dob = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
    hobby = models.ManyToManyField(Hobby)

    def __str__(self):
        return self.user.username

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

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

post_save.connect(create_user_profile, sender=User)

This is my forms.py file:

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'password', 'first_name', 'last_name')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('email', 'gender', 'dob', 'hobby')

This is my view function:

def register(request):
if request.method =="POST":
    userForm = UserForm(request.POST)
    profileForm = ProfileForm(request.POST)
    if userForm.is_valid() and profileForm.is_valid():
        userForm.save()
        profileForm.save()
        return redirect('/')
    else:
        return render(request, 'QMLove/register.html', {'userForm': userForm, 'profileForm': profileForm})
else:
    userForm = UserForm()
    profileForm = ProfileForm()
    return render(request, 'QMLove/register.html',{'userForm': userForm, 'profileForm': profileForm})

Thank you in advance!

Upvotes: 1

Views: 88

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You haven't done anything to associate the Profile you're creating with the User you've created. I would expect either two profiles two be created - one empty and one with data but not associated with the user - or for the profile form save to fail with an integrityerror because you didn't supply the user.

You should remove those signal receivers because they won't help with what you want to do and will probably create conflicts. Instead, pass the created user when you save the profile:

user = userForm.save()
profile = profileForm.save(commit=False)
profile.user = user
profile.save()

Upvotes: 1

Related Questions