Search code examples
pythondjangoone-to-one

IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id


Hi everybody :) I try to add a profile user in my application.The goal is to create a profile in the same time that we create an account. But This error come :

IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id I don't understand what is the probleme with my code because I have follow a youtube tutorial where this code works..

here is my code :

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import UserForm, ProfileForm
# Create your views here.

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        profile_form= ProfileForm(request.POST)

        if form.is_valid()  and profile_form.is_valid():
            user = form.save(commit=False)

            profile = profile_form.save(commit=False)
            profile.user = user

            user.save()
            profile.save()

            return redirect('account:login')

    else:
        form = UserCreationForm()
        profile_form = ProfileForm()


    context = {
     'form' : form ,
     'profile': profile_form,
    }

    return render(request, 'accounts/register.html', context)

models.py :

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

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    birthday = models.DateField()
    mail = models.EmailField(max_length=254, null = True, blank = True)


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

forms.py :

from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from .models import Profile

class LoginForm(AuthenticationForm):
    username= forms.CharField(label='Username', widget=forms.TextInput(attrs={'class':'form-control',
    }))
    password= forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control',
    }))


class UserForm(UserCreationForm):
    class Meta :
        model = User
        fields =('username','password1', 'password2')

class ProfileForm(forms.ModelForm):
    birthday= forms.DateField(label='birthday',widget=forms.DateInput(attrs={
    'class':'form-control',
    'type' :'date',
    }))

    class Meta :
        model = Profile
        fields =('birthday', 'mail')


Solution

  • Try:

    from django.shortcuts import render, redirect, get_object_or_404
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib import messages
    from .forms import UserForm, ProfileForm
    # Create your views here.
    
    def register(request):
        if request.method == 'POST':
            form = UserCreationForm(request.POST)
            profile_form= ProfileForm(request.POST)
    
            if form.is_valid()  and profile_form.is_valid():
                user = form.save(commit=False)
                user.save()
    
                profile = profile_form.save(commit=False)
                profile.user = user
    
                profile.save()
    
                return redirect('account:login')
    
        else:
            form = UserCreationForm()
            profile_form = ProfileForm()
    
    
        context = {
         'form' : form ,
         'profile': profile_form,
        }
    
        return render(request, 'accounts/register.html', context)