Reputation: 2022
Is there a common method/best practice/any means for combining forms that span multiple related models?
I want to create/edit model objects along with other, related model objects on the same page. Basically, being able to create/edit one model instance and another set of model instances related by a foreign key.
Not a great explanation, I know.
class Person(models.Model):
name = models.CharField(max_length=64, unique=True)
class PhoneNumber(models.Model):
person = models.ForeignKey(Person)
description = models.CharField(max_length=64, blank=True, null=True)
number = models.CharField(max_length=32, blank=True, null=True)
I want to be able to create/edit a person, along with all their associated phone numbers using a single form/page.
I've done this before using this nested form example, but it seems quite hackish.
Upvotes: 15
Views: 16476
Reputation: 6359
Yes! Use formsets, specifically https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
Upvotes: 12