开发者

Wrap a form and the realted inline_formeset with another formset

开发者 https://www.devze.com 2023-04-06 06:46 出处:网络
Sorry for the question title, i didn t know how to explain the question briefly. Basicly i m on a situation like this:

Sorry for the question title, i didn t know how to explain the question briefly.

Basicly i m on a situation like this:

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)

Wh开发者_运维问答at i'd like to do now, is to create a formset of authors. Each element should contain an istance of AuthorForm and the related book_formset.

Any idea on how to do it??

Thanks


This person may have done what you are asking about but I don't think it's what you need.

If I understand you correctly, you are close, but should be using the factory (not the factory generator function) multiple times to create a list where each element has two separate items: the author form and the inline formset with the books. The key point being you will have two separate items rather than one inside the other.

Each form/inline formset will need a unique prefix to identify it relative to the others in the rendered html/form soup.

In your view:

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))

Send the whole list to your template and:

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

You may even be able to skip the author form if django provides a form for the instance object in the formset. But I've never used them so I'm not sure.

I guess you have moved on since I found this late through a google search, but what did you eventually do?

0

精彩评论

暂无评论...
验证码 换一张
取 消