Using one form to save to muliple tables

Hi,

I’m using django forms for the first time.

As long as you use a single model for a form and no extra fields, it’s pretty straight forward.

But what if I want to use a few extra fields in a particular form?

Example with 3 models:

  1. User
  2. Organization
  3. Affiliation (relationship between Users and Organizations) – a user can have more than one affiliation

The create form is for a new user only.

Because it’s a new user, I want to be able to add an affiliation right away in the same form instead of making it in 2 steps. This implies that the user info will be saved in the user table (without the organization ID which doesn’t belong there). After the new User is saved, I need to grab the new user’s ID and the organization’s ID to populate the Affiliation table in one fell swoop.

I don’t know how to accomplish that. And, is it possible the way I’m describing it? Is there a better way?

Any help would be greatly appreciated.

No code, just high level explanation/concept would be enough.

Thanks,

A ModelForm is still a form, but with a couple of extra features.

This means that you can add fields to a form that aren’t part of any model.

However, you can’t combine two models in a single model form.

What you can do is display multiple Django forms within the same HTML form.
e.g.

<form ...>
{{ model_form_1.as_p() }}
{{ model_form_2.as_p() }}
</form>

So you’ve got all sorts of options available here.

I’ve seen a similar response from another source since yesterday. Seems like the way to go.

Thanks, I’ll look into it.