Using Javascript to dynamically add or remove a form within a Django formset

After reading @Paolo Bergantino's response to this specific question on SO, I have been attempting to dynamically include forms in my formset. However, I've noticed that the newly added form appears to be somehow connected to the previous one. When I click a checkbox on the new form, it affects the old form as well. Furthermore, when I submit, only one form is shown in the post. What happens to all the other newly added forms?

addAnother.js

function cloneMore(selector, type) {
    var newElement = $(selector).clone(true);
    var total = $('#id_' + type + '-TOTAL_FORMS').val();
    newElement.find(':input').each(function() {
        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
        var id = 'id_' + name;

        if ($(this).attr('type') != 'hidden') {
            $(this).val('');
        }
        $(this).attr({'name': name, 'id': id}).removeAttr('checked');
    });
    newElement.find('label').each(function() {
        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
        $(this).attr('for', newFor);
    });
    total++;
    $('#id_' + type + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);
}

template.html

{% load crispy_forms_tags %}
<script src="{{ STATIC_URL }}js/addAnother.js" type="text/javascript"></script>
<form action="{% url 'databank:register' %}" method="post" enctype="multipart/form-data">

<div class="container">
    <div class="row" style="margin-top: 30px"> 
      <div class="col-md-10 col-md-offset-1">
        {{ dataset_form.media }}
        {% crispy dataset_form %}
        {% crispy facility_form %}
        {% crispy contact_form %}

        {{ author_formset.management_form }}
        {% for form in author_formset.forms %}
        <div class='table'>
          <table class='no_error'>
          {{ form.as_table }}
          </table>
        </div>
        {% endfor %}
        <input type="button" value="Add More" id="add_more">

        {% crispy terms_form %}

      </div>
    </div>
  </div>

  <div class="container">
    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <a role="button" class="btn btn-lg btn-default" href="{% url 'databank:databank_home' %}">Cancel</a>
        <input type="submit" class="btn btn-lg btn-success pull-right" value="Proceed to Data Upload">
      </div>
    </div>
  </div>
</form>



<script type="text/javascript">
    $('#add_more').click(function() {
        cloneMore('div.table:last', 'service');
    });

Answer №1

Special thanks to Bill from the django-users community for guiding me towards successfully implementing django-dynamic-formset in my project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The representation of Django-extensions model graph can be visually depicted as a collection of square

During my project, I needed to visualize the database and found a recommendation to use django-extensions. Following the documentation, I took the following steps: I installed pyparsing and pydot using pip, then manually installed graphviz. Additionally, ...

Using cursor.execute() in Django to format raw queries for templates

I am in need of performing a raw query: cursor.execute("select id, name from people") results = cursor.fetchall() How can I modify this to be usable in a Django template: {% for person in results %} {{person.name}} {% endfor %} Typically, I would u ...

clicking on a link with the symbol "#" in the href attribute in Firefox prevents the setter

Good morning everyone, It's early Monday morning and I'm having trouble understanding why this particular line works in Internet Explorer but not in Firefox. <a class="button" href="#" onclick="setMaintenanceMode(false);">disable</a> ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Using the `type=file` input in Internet Explorer 11

Encountering an issue with the input type file on IE11. In IE11, the input field is displayed as two tab-able pseudo elements (text/button). Tried using the class ::-ms-browse to hide the button with display: none, but it remains tab-able. To replicate: ...

In search of a JavaScript library that can help format strings to meet the requirements of JSON formatting

Utilizing jQuery ajax, I am transmitting updates from the client's browser to my server. However, I have noticed that there are certain characters not supported by JSON that require an additional "\" in front of each one to be properly sent. The ...

The HighChart graphs are not rendering properly within a limited div size

I have integrated a JavaScript library called Highcharts to visualize JSON data on a line graph representing stock prices. If you are unfamiliar with the terms used in this post, refer to the image linked below for clarity: https://www.highcharts.com/image ...

The licensed Angular Google Map component is failing to display the map

I've been experimenting with the new Google Map component developed by the Angular Team (from the package @angular/google-maps) with the help of this insightful tutorial. Unfortunately, I'm facing an issue where the map isn't being displaye ...

Using jQuery to hide individual elements within a group of elements with the same class based on specific text contained within them

Here is a demonstration of the task at hand - the HTML code: <div id="section"> <div class="test-row"> <div class="row-copy-options"> <h4 class="text-capitalize"><b>Test Heading 1</b></h4> ...

Unable to invoke a function in JavaScript

When I try to create a user in the database by calling the function createOne inside createProfile, it seems like the function is not getting executed. Even though the route is functioning properly, I'm facing an issue with calling a function within a ...

Tips for integrating File Upload with an AJAX form in MVC 4

I am looking to incorporate a File Upload feature in MVC 4 that is compatible with all browsers including IE 8 or higher, Chrome, and FF. The key requirement is to have AJAX support, as I intend to integrate it within an AJAX.BeginForm. While I have foun ...

Creating dynamic Ionic slides by fetching data from a database

I am currently experimenting with Ionic. Web development is not my strong suit, so I may be a bit off the mark. However, I would like to retrieve data from an SQLite database and display it on an ion-slide-box. Here is what I have attempted: function sel ...

I need help figuring out how to navigate through Json data that has been transmitted from an Ajax call in

I'm struggling with passing a Json array object to a PHP file using Ajax. I need help on how to properly receive this data and loop through it in PHP. Here is an example of how I'm trying to retrieve the object, named main_data: // The data as ...

What are the optimal practices for handling form processing logic in Django when creating or updating models?

Looking to enhance the efficiency of my Django application by adhering to better coding practices. I often come across the advice to have fat models and thin controllers, especially after realizing that a significant portion of my display logic ended up in ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

What is the best way to send the input text to the filter component in my React application?

I am currently working on developing an application utilizing the "Rick and Morty API" to display a list of characters with various attributes such as gender, alive status, images, etc. My main goal is to implement a search bar that allows users to search ...

Upgrade your function to utilize Firebase V9 with Next.js framework

I recently updated my project to use version 9 of firebase, and since then, I've been encountering some code errors that I'm struggling to resolve. The previous function had the following structure, but now I need to update it to work with the n ...

Building an Angular 2 Template from a JSON Object

I have a project in Angular 2 where I need to display a map with local businesses fetched from the Yelp API. Although I can successfully retrieve the data, I am facing challenges when it comes to integrating it into my template. Should I convert the object ...

Is it necessary to update the HTML lang attribute when switching between languages dynamically?

I have a one-page website that loads an AngularJS application supporting multiple languages. All the pages on the site are generated in the browser using JavaScript after the initial HTML is fetched from the server. I'm aware of the importance of se ...

Hide the 1, 2, 3 page buttons in Datatables pagination and instead display only the Next and Previous buttons for navigation

I recently implemented datadables.net pagination for my HTML table. I am looking to customize the pagination buttons by hiding or removing the 1, 2, 3 ... buttons and only display Next and Previous Buttons. Is there a way to achieve this by setting paging ...