Django Crispy Forms向ModelFormSet添加新的空表单

时间:2017-09-01 16:30:32

标签: python django forms python-3.x django-crispy-forms

将新的空表单添加到具有现有表单的modelformset的最简洁方法是什么?

forms.py:

class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

MyFormSet = modelformset_factory(MyModel, extra=1, exclude=(), form=MyForm)

class MyFormsetHelper(FormHelper):
    def __init__(self, *args, **kwargs):
        super(MyFormsetHelper, self).__init__(*args, **kwargs)
        self.form_method = 'post'
        self.template = 'bootstrap/table_inline_formset.html'
        self.add_input(Submit("submit", "Save"))
        self.add_input(Button("add", "Add New"))

模板:

{% extends "base.html" %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block stylesheets %}
  {{ block.super }}
{% endblock stylesheets %}
{% block content %}
  {% crispy formset helper %}
{% endblock content %}

我有一个添加按钮,但我不知道如何将其与动作联系起来。我也不知道脆弱的形式会创造一个空的形式。在发现脆弱的表单之前,我写了所有模板代码并使用类似下面的内容来呈现空表单。

<div id="empty_form" style="display:none">
      <table class='no_error'>
        <tr>
          <td>{{ modelformset.empty_form.Field1 }}</td>
          <td>{{ modelformset.empty_form.Field2 }}</td>
          <td>{{ modelformset.empty_form.Field3 }}</td>
        </tr>
      </table>
    </div>
<input type="button" value="Add" id="add_more">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
      $('#add_more').click(function() {
          var form_idx = $('#id_form-TOTAL_FORMS').val();
          $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
          $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
      });
  </script>

如果没有这么简单的方法,有没有办法将上面的代码与香脆的formset结合起来?我试过了,但没有任何反应。

感谢您提供任何可能的见解。

1 个答案:

答案 0 :(得分:0)

我使用此代码并且它工作正常...

按钮

<input type="button" value="Add" id="add_more" onclick="add_form('empty_form')">

javascript

<script>
  function add_form(formset) {
    let total = $("#id_" + formset + "-TOTAL_FORMS").val();
    let row = $("#" + formset + "_table tr:last")[0]; // find row to copy
    let table = $("#" + formset + "_table tbody")[0]; // find table to append to
    let clone = row.cloneNode(true); // copy children too
    clone.innerHTML = clone.innerHTML.replaceAll("-" + (total - 1) + "-", "-" + total + "-");
    table.appendChild(clone); // add new row to end of table
    $("#id_" + formset + "-TOTAL_FORMS").val(++total);
  }
</script>