用另一个表单集包装表单和相关的inline_formset



很抱歉问题的标题,我不知道如何简单地解释这个问题

基本上是这样的情况:

models.py

class Author(Model):
    ...
class Book(Model)
    author = models.ForeignKey(Author)

views.py

for author in Author.objects.filter(name=""):
    author_form = AuthorForm(instance=author) #This is a model form
    book_formset = inlineformset_factory(Author, Book, instance=author)

我现在要做的是创建一个作者的格式集。每个元素应该包含一个实例AuthorForm和相关的book_formset。

你知道怎么做吗??

谢谢

这个人可能做了你要求的事情,但我认为这不是你需要的。

如果我理解正确的话,您已经接近了,但是应该多次使用工厂(而不是工厂生成器函数)来创建一个列表,其中每个元素都有两个单独的项:作者表单和带有书籍的内联表单集。关键是你将有两个独立的项目,而不是一个在另一个里面。

每个表单/内联表单集都需要一个唯一的前缀,以便在呈现的html/表单中相对于其他表单集进行标识。

在你看来:

AuthorBooksFormSet = inlineformset_factory(Author, Book)
author_books_list = list()
for author in author_queryset: #with whatever sorting you want in the template
    prefix = #some unique string related to the author
    author_form = AuthorForm(instance=author,
                             prefix='author'+prefix)
    author_books_formset = AuthorBooksFormSet(instance = author,
                                              prefix = 'books'+prefix)
    author_books_list.append((author_form, author_books_formset))

将整个列表发送到您的模板和:

{% for author_form, author_books_formset in author_books_list %}
    ...something with author_form
    ...something with author_books_formset
{% endfor %}

如果django在formset中为实例对象提供了一个表单,你甚至可以跳过author表单。但我从来没用过,所以我不确定。

我猜自从我通过谷歌搜索发现这篇文章后,你已经离开了,但你最终做了什么?

最新更新