嵌套形式我的功能,我需要實現與以下車型和Django
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'}
與上述型號的形式
所以嵌套Django表單,我需要在同一屏幕上動態創建表單,如下面的UI屏幕
因此,從上面的屏幕中,我們可以觀察到所有三個模型窗體應該顯示在同一頁面上。
1. The publisher may have many authors
2. Each author may have many books
您也可以從設計觀察,我們有
1.Add Another Author - Adding Multiple Authors
2.Add Book - Adding multiple books for Author
2.兩個按鈕添加圖書
當我們單擊添加圖書,新的圖書形式應該是創建截圖爲
1.添加另一個作者
當我們點擊Add another author
按鈕,一個新的作者記錄應顯示他可以能夠爲筆者上面一樣通過點擊Add Book
新增多本圖書。如果我們只有兩個型號A和B,如果B已經ForeignKey
到A,那麼我們可以能夠通過usign Django的formsets or inline_formsets or model_formsets
來實現這一目標functionlaity,但這裏在上面,我們應該能夠
- 添加嵌套(多個)
Book
形式爲Author
- 添加巢ED(多)
Author
形式爲出版商
那麼如何實現上述功能呢?,我尋覓了很多,但不能能找出上述東西
通過'字符替換'Charfield'你的代碼示例 – juliocesar