内部FormSet需要手动刷新请求 [英] Inner FormSet requires manual refreshing from request

查看:61
本文介绍了内部FormSet需要手动刷新请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到嵌套在另一个表单中的FormSet的行为异常。

示例应用程序:

I noticed weird behaviour of FormSet which is nested inside another form.
Sample app:

####   forms:   ####

class BookForm(forms.Form):
    title = forms.CharField()


BookFormSet = formset_factory(BookForm, extra=3)


class PublisherForm(forms.Form):
    name = forms.CharField()
    books = BookFormSet(prefix='books')

用于显示表单的基于类的视图:

Class-based view for displaying forms:

####   views:   ####

class PublisherCreateView(FormView):
    template_name = 'library/create.html'
    form_class = PublisherForm

    def form_valid(self, publisherForm):
        # workaround: somehow publisherForm's inner list need to be restored from POST request:
        # otherwise it'll be empty FormSet as if it was constructed using BookFormSet(prefix='books')
        books = BookFormSet(self.request.POST, self.request.FILES, prefix='books')
        publisherForm.books = books
        do_sth_fancy_dancy_with(publisherForm)
        return super(PublisherCreateView, self).form_valid(publisherForm)

用于显示PublisherForm的模板:

An the template used for displaying PublisherForm:

####   template:   ####

<form action="." method="post">{% csrf_token %}
    <div class="section">
        {{ form.as_p }}
    </div>

    <h2>Books</h2>
    <div class="books">
        {{ form.books.as_p }}
        <p><input type="button" id="add-row" value="Add another book"/></p>
    </div>

    <input type="submit" value="Save"/>
</form>

如果我在form_valid中省略了前两行,则该列表在浏览器中被修改后不会受到影响。

一个很好的解释,为什么会这样,否则我的代码的修改可能会受到赞赏

If I omit first 2 lines in form_valid the list is untouched by its modification in a browser.
A nice explanation why is this happening, or maybe amend of my code would be more than appreciated

推荐答案

I我不确定为什么您会认为它还能做其他事情。不支持在表单内部嵌套表单集(或其他表单),文档中没有任何暗示。在这种情况下,Django必须专门包含代码以使用帖子中的数据实例化表单集,而事实并非如此。

I'm not sure why you think it would do anything else. Nesting formsets - or other forms - inside forms is not supported, and there is nothing in the documentation to imply it is. Django would have to specifically include code to instantiate the formset with data from the post in that situation, and it doesn't.

这篇关于内部FormSet需要手动刷新请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆