I have functionality where i need to implement nested django forms with the below 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'}
So with the above models and forms, i need to create the forms dynamically on the same screen like in the UI screen below
So from the above screen, we can observe all the three model forms should displayon the same page.
1. The publisher may have many authors
2. Each author may have many books
Also you can observe from the design, we have two button for
1.Add Another Author - Adding Multiple Authors
2.Add Book - Adding multiple books for Author
2. Add Book
When we click on Add Book, a new Book form should be created as in the screenshot
1. Add another Author
When we click on Add another author
button a new Author record should be displayed and he can able to add multiple Books for this author same as above by clicking on Add Book
If we have only two models A and B, and if B has ForeignKey
to A, then we could be able to achive this functionlaity by usign django formsets or inline_formsets or model_formsets
, but here in the above we should be able to
- Add nested(multiple)
Book
forms forAuthor
- Add nested(multiple)
Author
forms for Publisher
So how to achieve the above functionality ?, i have searched a lot, but could n't able to figure out the above stuff