Search code examples
pythondjangodjango-formwizard

Django Model Wizard : IntegrityError Column "user_id" cannot be null


I get a slight problem when trying to use django wizard and I am scratching my head to solve it

Here is my model:

class Profile(models.Model):
    profile_user = models.OneToOneField(User,db_index=True)
    studio = models.ForeignKey(Account)

And here is my wizard.py:

from django.utils.translation import ugettext_lazy as _
from django.forms.models import modelform_factory
from formtools.wizard.views import SessionWizardView
from .models import *

class NewModelWizard(SessionWizardView):
     form_list = [
         (_('New model registration'),modelform_factory(User, fields=('username','password'))),
         (_('Model data'), modelform_factory(Profile))
     ]
template_name = "create_profile.html"

def done(self,form_list, **kwargs):
    user = form_list[0].save()
    profile = form_list[1].save(commit=False)
    profile.studio = self.request.user.account
    profile.user = User.objects.get(id=user.id)
    profile.save()

After submitting the wizard, I encounter the following error:

IntegrityError : (1048, "Column 'profile_user_id' cannot be null")

I don't see what I am doing wrong here, does anybody get a clue about what is happening and how to fix it ?


Solution

  • Your field name is profile_user, so use that.

    profile.profile_user = user
    

    Note you don't have to refetch the user from the db, just use user.