Alan Tingey
Alan Tingey

Reputation: 971

Django -> Exception Value: (1048, "Column 'user_id' cannot be null")

I have the following view which works perfectly:

@transaction.atomic
def register(request):
    next_url = request.POST.get('next', request.GET.get('next', reverse('profile')))
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        profileform = ProfileForm(request.POST)
        if form.is_valid() and profileform.is_valid():
            new_user = form.save()

            # Login the newly created user.
            authenticated_user = authenticate(username=new_user.username,
                                              password=form.cleaned_data['password1'])
            login(request, authenticated_user)
            return redirect(next_url)
    else:
        form = RegistrationForm()
        profileform = ProfileForm()
    return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url})

However, when I wish to save the additional profile information using the following line (placed below the line new_user = form.save() ):

    new_user_profile = profileform.save()

I get the following error:

Exception Type: IntegrityError
Exception Value: (1048, "Column 'user_id' cannot be null")

My model for the profile is as follows:

class Profile(models.Model):
    user = models.OneToOneField(User)
    dob = models.DateField(max_length=8)

    class Meta:
        managed = True
        db_table = 'fbf_profile'

Any help would be great, Alan.

Upvotes: 0

Views: 6503

Answers (2)

2ps
2ps

Reputation: 15956

When working with foreign keys like this you typically see a save with commit=False and then setting the foreign keys on the model manually. e.g.,

new_user = form.save()
profile = profileform.save(commit=False)
if profile.user_id is None:
    profile.user_id = new_user.id
profile.save()

This save() method accepts an optional commit keyword argument, which accepts either True or False. If you call save() with commit=False, then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.

Upvotes: 5

gitaarik
gitaarik

Reputation: 46370

Apparently the user field is not set in the ProfileForm. The Profile model needs a user_id for the user OneToOneField.

The ProfileForm will need a user field that you'll have to set, or you'll have to manually set the user field in the save() function of ProfileForm (which you would then have to override).

Upvotes: 0

Related Questions