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
userto generate its auto-incremented ID. - Assigning
profile.user = userconnects the two objects, filling in the requireduser_idfield. - Now when you save
profile, it has a valid value foruser_id, so the database constraint is satisfied.
内容的提问来源于stack exchange,提问作者Aditya singh rathore
相关产品推荐
相关产品推荐

