You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django用户注册成功但雇主表单存失败:user_id非空约束报错

Fix: Null Value in "user_id" When Saving Employer Form Data

Hey, let's sort out why your employer form data isn't saving—this error is pretty straightforward once you spot the missing link!

Why This Happens

Your EmployerUser model has a required foreign key user pointing to the User model. Right now, when you save the profile with profile.save(), you haven't connected it to the newly created User instance yet. That leaves the user_id column empty, which violates the database's not-null constraint (the error message even shows the failing row has null in that spot).

The Fix

You just need to link the saved User to your EmployerUser profile before saving it. Here's the updated register_view code:

def register_view(request):
    next = request.GET.get('next')
    form = UserRegisterForm(request.POST or None)
    profileform = EmployerUserForm(request.POST or None)
    if form.is_valid() and profileform.is_valid():
        user = form.save(commit=False)
        profile = profileform.save(commit=False)
        password = form.cleaned_data.get('password')
        user.set_password(password)
        user.save()  # User is now saved to the database and has an ID
        profile.user = user  # Link the new User to the EmployerUser profile
        profile.save()  # Now profile has a valid user_id, so save succeeds
        new_user = authenticate(email=user.email, password=password)
        login(request, new_user)
        if next:
            return redirect(next)
        return redirect('login')
    context = {
        'form': form,
        'profileform': profileform,
    }
    return render(request, "registration/signup.html", context)

Quick Breakdown

  • Using save(commit=False) creates the model object in memory but doesn't write it to the database yet.
  • You first save the user to generate its auto-incremented ID.
  • Assigning profile.user = user connects the two objects, filling in the required user_id field.
  • Now when you save profile, it has a valid value for user_id, so the database constraint is satisfied.

内容的提问来源于stack exchange,提问作者Aditya singh rathore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:34:47