I have a requirement to implement nested Django forms using the following models:
class Publisher(models.Model):
name = models.CharField(max_length=256)
address1 = models.CharField(max_length=256)
address2 = models.CharField(max_length=256)
city = models.CharField(max_length=256)
class Author(models.Model):
publisher = models.ForeignKey(Publisher)
name = models.CharField(max_length=256)
address = models.CharField(max_length=256)
class Book(models.Model):
author = models.ForeignKey(Author)
name = models.CharField(max_length=256)
price = models.FloatField()
forms.py
class PublisherForm(ModelForm):
class Meta:
model = Publisher
def __init__(self, *args, **kwargs):
super(PublisherForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Publisher Name', 'autofocus':'autofocus'}
self.fields['address'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Publisher Address '}
class AuthorForm(ModelForm):
class Meta:
model = Author
exclude = ('publisher',)
def __init__(self, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Author Name'}
self.fields['address'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Author Address'}
class BookForm(ModelForm):
class Meta:
model = Book
exclude = ('author',)
def __init__(self, *args, **kwargs):
super(BookForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Book Name'}
self.fields['price'].widget.attrs = {'id':'inputIcon', 'class':'input-block', 'placeholder':'Book Price'}
To achieve this functionality, I need to create dynamic forms on the same screen as shown in the UI below.
On the above screen, all three model forms should be displayed together.
1. A publisher may have many authors
2. Each author may have many books
You'll notice from the design that there are two buttons for
1. Add Another Author - Adding Multiple Authors
2. Add Book - Adding multiple books for Author
2. Add Book
By clicking on the Add Book button, a new Book form should be created as shown in the screenshot
1. Add another Author
Clicking on Add another author
will display a new Author record where you can add multiple Books for this author by clicking on Add Book
In cases where we have only two models A and B, and if B has a ForeignKey to A, this functionality could be achieved using Django formsets or inline_formsets or model_formsets. However, in our case, we need to
- Add nested(multiple)
Book
forms forAuthor
- Add nested(multiple)
Author
forms for Publisher
How do we accomplish the above functionality? I've searched extensively but haven't been able to figure it out yet.