Django 内联表单集只保存三个对象

Django Inline formsets only saving three objects

我有一个问题对象,它有一个讨论对象的外键字段。我正在尝试使用讨论 ModelForm 和问题内联表单集来呈现表单。当它向页面呈现一个空表单时,一切正常,所有字段都在它们需要的位置。错误是我有 JQuery 允许用户根据需要添加更多问题,方法是附加 html 与具有适当名称值的其他问题输入和标签完全相同。它最初只是为问题放置了三个空白文本区域。在我的视图函数中,我保存了讨论模型表单和带有 request.POST 数据的内联表单。我可以在 POST 中看到所有数据,甚至添加的问题都在那里,但是当我将它们重定向到页面以查看新讨论对象及其相关字段的只读版本时,总是有只有三个问题,而不是 4+。

查看

def new_discussion(request):
    member = get_member(request)

if request.method == 'POST':
    form = DiscussionForm(data=request.POST)
    QuestionInlineFormSet = inlineformset_factory(Discussion, Question, fields='__all__')

    if form.is_valid():

       created_discussion = form.save(commit=False)
       formset = QuestionInlineFormSet(request.POST, instance=created_discussion)
       if formset.is_valid():
            created_discussion.community = member.community
            created_discussion.save()
            formset.save()

            return HttpResponseRedirect('/user/discussions/')

模板

{% extends 'member/discussions.html' %}

{% block extra-head %}
    <script src='//cdn.tinymce.com/4/tinymce.min.js'></script>
    <script>

    var count = {{ questions|length }};

    $(document).ready(function(){
      $('#add_question').on('click', function(e){
            e.preventDefault()
            console.log(count)

            var form = $('.form-data')
            form.append('<div class="col-xs-12 extra-' + count + ' form-group"></div>')
            $('#question-count').val(count)

            var extra = $('.extra-' + count)
            extra.append('<label for="id_question_set-' + count + '-question">Question:</label>')
            extra.append('<textarea cols="40" id="id_question_set-' + count + '-question" maxlength="200" name="question_set-' + count + '-question" rows="10"></textarea>')
            extra.append('<label for="id_question_set-' + count + '-scripture">Scripture:</label>')
            extra.append('<input id="id_question_set-' + count + '-scripture" maxlength="30" name="question_set-' + count + '-scripture" type="text">')
            extra.append('<label for="id_question_set-' + count + '-display_order">Display order:</label>')
            extra.append('<input id="id_question_set-' + count + '-display_order" name="question_set-' + count + '-display_order" type="number" value="1">')
            extra.append('<label for="id_question_set-' + count + '-DELETE">Delete:</label>')
            extra.append('<input id="id_question_set-' + count + '-DELETE" name="question_set-' + count + '-DELETE" type="checkbox">')
            extra.append('<input id="id_question_set-' + count + '-discussion" name="question_set-' + count + '-discussion" type="hidden">')
            extra.append('<input id="id_question_set-' + count + '-id" name="question_set-' + count + '-id" type="hidden">')
            count += 1
        })
    })

    tinymce.init({
        selector: '#id_content',
        plugins : 'media code',
        media_alt_source: true,
        media_poster: false,
        media_dimensions: false
      });

</script>
{% endblock %}

{% block discussion %}

<form method='POST' id='discussion-form'>

    <div class="form-data">

        {% csrf_token %}

        <div class='col-xs-12 form-group'>
            <label for='id_title'>Title</label>
            {{ form.title }}
        </div>

        <div class='col-xs-12 form-group'>
            <label for='mytextarea'>Content</label>
            {{ form.content }}
        </div>

        <div class='col-xs-12 form-group'>
            <label for='id_audio'>Audio</label>
            {{ form.audio }}
        </div>

        <input type="hidden" id="question-count" name="question-count" value='0'>

        <div class="col-xs-12">
            {{ questions }}
        </div>

    </div>

    <button class="btn btn-info" style="margin-left: 15px; margin-bottom: 10px;" id="add_question">Add Question</button>

    <br>

    <div class='btn-wrapper col-xs-12'>

        <input id='save' type='submit' class='btn btn-primary' style="margin-right: 10px;" value='Save' />

        {% if view %}
            <a class='btn btn-primary' style="margin-right: 10px;" href='/user/discussions/edit/{{ discussion.id }}/preview/'>
            View
        </a>
        {% endif %}

        <!-- <input id='preview' type='submit' class='btn btn-primary' style="margin-right: 20px;" value='Preview' /> -->
        <a href="/user/dashboard" class='btn btn-warning'>Back to dashboard</a>

    </div>

</form>

{% block discussion_nav %}

{% endblock %}

{% endblock %}

您需要更新管理表单中指定表单总数的隐藏字段。每次添加表单时都需要更新它。您可以使用 id:

来定位它
id_form-TOTAL_FORMS

目前,您的 count 变量是在页面加载时分配的(似乎是 3 种形式)。 Django 正在验证您的表单集以仅接受指定数量的表单,因此删除所有其他表单集表单。所以每次添加表单时,都需要将其递增 1。

以下是有关管理表单的一些信息:https://docs.djangoproject.com/en/dev/topics/forms/formsets/#understanding-the-managementform