Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Crispy Forms Add New Empty Form to ModelFormSet

What is the crispiest way to add a new, empty form to a modelformset with existing forms?

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

template:

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

I have an add button, but I don't see how to tie that to an action. I also don't know how crispy forms would create an empty form. Prior to discovering crispy forms, I was writing out all the template code and used something like the below to render the empty form.

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

If there's no crispy way to do this, is there a way to combine the code above with the crispy formset? I tried, but nothing happens.

Thank you for any insight you all might have.

like image 247
OverflowingTheGlass Avatar asked Nov 26 '25 23:11

OverflowingTheGlass


1 Answers

I use this code and it works fine...

button

<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>
like image 54
quijoT Avatar answered Nov 29 '25 15:11

quijoT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!