e-Jah
e-Jah

Reputation: 335

Use a form inside a form or How to work with foreign keys in forms

I am going to use the documentation model as an example:

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    # ...

class Manufacturer(models.Model):
    # ...

Let's say I want to create a form to add a new Manufacturer, and in this form I want to be able to add new cars. How would it be done with django-forms?

Is it even possible?

Thank you in advance for your help!

Upvotes: 1

Views: 2087

Answers (1)

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

The short answer:

You want modelformset_factory, documented here: http://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#model-formsets

The still-rather-short answer, but with a couple of gotchas to watch for:

On the processing side, if you're creating both the Manufacturer and the multiple Car instances, you'll want to be sure to save the manufacturer first, before saving the individual cars (which must reference the manufacturer). Make sure this happens in a database transaction if you can help it.

One more note: if this is a bit confusing to you, beat in mind that there's no hard and fast rule saying that you can only process one form in a request. You just have multiple forms.Form (or subclasses thereof) objects within the HTML <form> tag, which posts to a single request location that processes each form individually and saves them out. Again, use a database transaction so that if something fails at the end, the entire thing gets rolled back and the user can correct their error without having bad or orphan data in the database.

Upvotes: 1

Related Questions