Adding forms when using Django modelformset_factory

15 views Asked by At

I start using Django's modelformset_factory. I want to use it to add a number of records to my Shift model. what I simply want is to have 3 buttons (maybe 4)

  1. Add empty form
  2. Copy last form (when only a few things need to be changed)
  3. Save
  4. (Optional) Delete record

I thought this was all intended to be part of the modelformset_factory but I learned I need javascript to do this. Here is my attempt to get this done:

<script>
        $(document).ready(function () {
            $('.js-example-basic-single').select2();
        });
    </script>

    <script>
        $('#add-more-btn').click(function () {
            const newForm = $('#formset-container').children().last().clone();
            // Increment indices and update IDs/names in new form
            newForm.find('input, select').each(function () {
                const name = $(this).attr('name');
                if (name) {
                    const formIndex = parseInt(name.match(/form-\d+$/)[0].match(/\d+$/)[0]);
                    const newIndex = formIndex + 1;
                    $(this).attr('name', name.replace(/form-\d+$/, `form-${newIndex}`));
                    $(this).attr('id', name.replace(/form-\d+$/, `form-${newIndex}`));
                }
            });
            // Re-initialize Select2
            newForm.find('.js-example-basic-single').select2();
            newForm.appendTo('#formset-container');
        });
    </script>
{% extends 'base.html' %}

{% load static %}

{% block additional_css %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/form.css' %}">
{% endblock %}

{% block content %}

    <form method="post" id="formset">
        {% csrf_token %}
        {{ formset.management_form }}

        <div id="formset-container">
            {% for form in formset %}
                <div class="formset-form">
                    {{ form.as_p }}
                </div>
            {% endfor %}
        </div>
        <button type="button" id="add-more-btn">Add Shift</button>
        <button type="submit">Save shifts</button>
    </form>

I get this console error: Uncaught TypeError: Cannot read properties of null (reading '0')

Related to this line: const formIndex = parseInt(name.match(/form-\d+$/)[0].match(/\d+$/)[0]);

I know this whole formset approach works with dynamic ID's but My knowledge is limited to solve this. Any help would be appreciated.

0

There are 0 answers