In Django, I want to create a form that involves 2 Models
- a Library
model and a Book
model. The Library
can contain multiple Book
s.
class Library(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
for_library = models.ForeignKey(Library, null=False, on_delete=models.PROTECT)
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
Now, I have created a Library
with id=1
and now want to create a form to tag multiple books to the library. How can I create the form such that the fields look like (including pre-filling the library ID):
Library: <id=1 Library>
Book1 Title: _____
Book1 Author: _____
Book2 Title: _____
Book2 Author: _____
The furthest I have gone is:
BookFormset = inlineformset_factory(Library, Book,
fields=['title', 'author'], form=CreateBookForm, extra=2, min_num=1, max_num=20,
can_delete=True)
But cannot continue and am not sure of integrating this with views.py
. Any help on this?