[Answered ]-Django forms: two form models in one <form> with a foreign key

2👍

Just use pass in False for the commit kwarg into the privilegeForm’s save call. This will return the privilege object without saving it. Then you can assign the user object to it that was created, and then call save on privilege to commit to the database.

See: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

userForm = UserForm(data=request.POST)
privilegeForm = PrivilegeForm(data=request.POST)
if userForm.is_valid() and privilegeForm.is_valid():
  user = userForm.save()
  privilege = privilegeForm.save(commit=False)
  privilege.user = user
  privilege.save()
👤Tareq

Leave a comment