Sending data from multiple HTML table rows at once to a Django model

After a user selects items from a list, they can submit the selected items to be saved in a table. The table is dynamically rendered using JavaScript and the data comes from a Map with keys as primary keys and values as descriptions and prices.

function displaySelectedItems(value, key, map) {
    var newRow = document.createElement("tr");
    var itemPK = document.createElement("td");
    itemPK.setAttribute('class', 'id');
    itemPK.textContent = key;
    newRow.appendChild(itemPK);
    
    var itemDescription = document.createElement("td");
    itemDescription.textContent = value.item;
    newRow.appendChild(itemDescription);
    
    var itemPrice = document.createElement("td");
    itemPrice.textContent = value.price;
    newRow.appendChild(itemPrice);
    
    selectedItemsTableBody.appendChild(newRow);

  }
});

The HTML representation of the table;

        <div class="table-responsive">
          <table class="table table-borderless" id="selected_items_table">
            <thead>
              <tr>
                <th>Description</th>
                <th>Price</th>
                <th>Remove</th>
              </tr>
            </thead>
            <form action="" method="POST"> {% csrf_token %}
            <tbody id="selectedItemsTable">
              <!-- SELECTED ITEMS ARE DISPLAYED HERE -->
            </tbody>
            </form>
          </table>
        </div>

Django Model Structure

class Selected(models.Model):
    foreignKey = models.CharField(max_length=5)
    description = models.CharField(max_length=20)
    price = models.DecimalField(max_digits=5, decimal_places=2)

I'm unsure how to save the table rows in the model or whether it should be done in the view to maintain model simplicity. Is it feasible to save data from multiple table rows with one submit button?

Some example data:

Pk . Description . Price

12 . Pizza . 13.50

13 . Water . 3.00

Any suggestions would be appreciated. Thank you!

Answer №1

With Django's built-in functionality for managing multiple elements on a single page, utilizing formsets can streamline the process without the need for client-side rendering. Formsets allow you to handle numerous forms efficiently within your current project setup.

However, if you prefer to continue with client-side rendering, consider generating the formset dynamically on the client side while still utilizing the server-side machinery to handle the data processing seamlessly.

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

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

Occasionally, the function `Element.getElementByTag("mytag")` may come up empty

Here is the outer html of Element1 in CKeditor: <element1 id="s1"> <mytag>Test1</mytag> <span> </span> Some text <mytag>Test</mytag> <span> </span> <mytag>Test3</mytag> some text <span&g ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

Learn how to increase spacing in React applications

I'm currently utilizing the Grid component from @material-ui to present my data. Within this Grid, I have several nested grids, each representing a different section. I've implemented the container spacing attribute of the Grid and set it to the ...

Is there a way to access a JSON node dynamically without relying on the eval function?

Path variables can be unpredictable, ranging from just a to a/b, and even a/b/c. My goal is to dynamically reach a node based on the path provided. The code snippet below achieves this, but I am open to exploring alternative methods that do not involve usi ...

The lack of functionality for lockOrientation in Cordova is causing issues

Currently working with Cordova, I am attempting to set the screen orientation to landscape for Android. Utilizing the screen-orientation plugin found at: https://www.npmjs.com/package/cordova-plugin-screen-orientation In my JavaScript code, I have impleme ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

Encountering issues when attempting to install vue-cli on a new project

After creating an empty project, I attempted to install vue-cli using the command npm install -g @vue/cli. However, during the installation process, I encountered the following errors and warnings from the interpreter: npm WARN read-shrinkwrap This versi ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

How can I ensure that my function only returns a value once the ajax call has finished?

Using mootools, I have a function that triggers an ajax script to retrieve a value. However, the function seems to return before the AJAX call is completed! What could be causing this issue... function getCredits() { var loadGlobalTab = new Request.J ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Browsing through different backdrop visuals

I realize this question has been brought up numerous times before, but I urge you to take a moment and read through it. Currently, I am looking to add more interactivity to my HTML page. My goal is to change the background image every five seconds with a ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

Retrieving HTML content using scriptJS

Currently utilizing VueJS and encountering an issue after compiling code in production mode. I have one index.html file and several assets that are being uploaded to the cloud. The challenge lies in the fact that the client is not accepting the HTML file ...

Utilizing Vue to Customize Chart Settings with Data

I'm currently working on hitting a rest api to retrieve a dataset for a specific piece of equipment. However, I'm struggling to extract the first column of data as an array. I've attempted using computed and methods in vue, but I constantly ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

Starting the download of the canvas featuring a stylish border design

I'm facing an issue where the canvas border is not showing up when I download the canvas with a border. The border appears on the screen, but it doesn't get included in the downloaded canvas. let canvas=qrRef.current.querySelector("canvas&qu ...

Adjust the map automatically as the cursor approaches the map's edge in Google Maps API V3

My latest project involved creating a selection tool using the Rectangle shape tool. With this tool, users can easily select markers by drawing a rectangle over them and releasing their mouse to erase the selection (similar to selecting items on a desktop ...