Django OneToOne Profile/User relationship not saving

Question:

I’m trying to set up a Django blogging app to use a one to one relation from User’s to a Profile model in order to capture mode information than the default Django User model. The problem Im having is that my Profile model isn’t saving, and my profile table remains unchanged despite successfully signing up a User.
Here’s my view where this happens:

@transaction.atomic
def profile_new(request):
    if request.method == "POST":
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            profile = profile_form.save(commit=False)
            user.username = user.email
            user.set_password(user.password)
            user.save()
            profile.user = user
            profile.save()
            return redirect('profile_detail', pk=user.pk)
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        user_form = UserForm()
        profile_form = ProfileForm()
    return render(request, 'accounts/update.html', {
        'user_form': user_form,
        'profile_form': profile_form
    })

Pretty straightforward, runs with no errors at all, it just never actually saves the Profile object.
heres the forms:

from django import forms
from .models import User, Profile

class UserForm(forms.ModelForm):
    """confirm_password = forms.CharField()"""
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password')

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('bio', 'birth_date', 'avatar', 'location')

And the model for Profile:

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    bio = models.TextField(max_length=500, blank=True)
    avatar = models.ImageField(upload_to = 'avatars/', default = 'avatars/default.jpg')
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

Does anyone see any reason why Profile wouldn’t save?
My second question is: whats the right way to save and hash that password? I’ve figured out I can add a temporary ‘confirm password’ field to the form, but I’m not how to hash and save the password I get.

Asked By: Owen Percoco

||

Answers:

Try code below:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True,null=True)

I think your profile table can not save the new record if user field is empty!

Answered By: nick

I came across the same issue too the form information doesn’t save at the back end unless it manually save at the django admin interface please some help us on this its has really been toxic for me

Answered By: Aigustin