Executing the .delete() queryset in Django within a ListView: Best Practices

After much work and effort, I have implemented the following functionality:

1.) I have successfully developed a JavaScript function that extracts the IDs of the items from the database, using checkbox selection in DataTables:

function () {
    // count check used for checking selected items.
    var count = table.rows( { selected: true } ).count();

    // Count check.
    // Count must be greater than 0 to delete an item.
    // if count <= 0, delete functionality won't continue.
    if (count > 0) {
        var data = table.rows( { selected: true } ).data();

        var list = []; 

        for (var i=0; i < data.length ;i++){
           // alert(data[i][2]);
           list.push(data[i][2]);
        }

        var sData = list.join();

        // alert(sData)
        document.getElementById('delete_items_list').value = sData;
        }
}

This function produces a result such as 1,2,5,7 based on the selected rows.

2.) I have stored these values within an <input type="hidden"> field.

Recently, I came across a solution for deleting data from a Django database using checkboxes, and I am intrigued by its potential application.

My assumption is that the integration should take place within the ListView I created. But how do I implement it such that clicking the "Delete selected items" button executes similarly to the provided answer?

I aspire to replicate the functionality seen in Django Admin when deleting items.

Here is a glimpse of my ListView: https://i.sstatic.net/xrSGO.png

Answer №1

Certainly! You can utilize a linked example for this purpose. Similar to Django Admin, you can send selected IDs and Django will filter based on the given values before applying the chosen action to the selected items.

UPDATE

Here's an example:

class List(ListView);
    def post(self, request, *args, **kwargs):
        ids = self.request.POST.get('ids', "")
        # ids are in the format of a string e.g. "1,2,3,4"
        ids = ids.split(",")
        try:
            # Check if the ids are valid numbers
            ids = map(int, ids)
        except ValueError as e:
            return JsonResponse(status=400)
        # delete items
        self.model.objects.filter(id__in=ids).delete()
        return JsonResponse({"status": "ok"}, status=204)

And the corresponding HTML:

<button id="delete-button">Del</button>
<div id="items-table">
      {% for object in objects_list %}
           <div class="item" data-id="{{object.id}}">{{ object.name }}</div>
      {% endfor %}
</div>
<script>
     $(function(){
         $('#delete-button').on('click', function(e) {
             // Retrieve selected items. Make sure to adjust this based on your template structure.
             var ids = $.map($('#items-table item'), function(item) {
                   return $(item).data('id')
             }).join(',');
             $.ajax({
                 type: 'POST',
                 url: window.location.href ,
                 data: {'ids': ids},
                 success: function (res) {
                     // Update the page
                     window.location.href = window.location.href;
                 },
                 error: function () {
                  // Display a message or handle the error
                 }
             });
         })
     })();
</script>

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

AttributeError: 'Module' Object Does not Contain 'models' Attribute

Just starting out with python and encountered this code: from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) ...

Sending specific names as properties

Looking to streamline my repetitive form inputs by abstracting them into a component, I want the following functionality: <InputElement title="someTitle" v-model="someName" @blur="someFunction" name="someName" type="someType"> The desired output wo ...

Problem identified with Vue.js: The Log in screen briefly flashes before redirecting the authenticated user (resulting in a full page refresh)

My routing is functioning properly, utilizing navigation guards to prevent users from accessing the login or register routes once they are signed in. However, when I manually type '/auth/signin' in the address bar, the login screen briefly appear ...

How to Retrieve a Specific Line with jQuery

Could jQuery be used to retrieve the offset of the first letter in the 5th visual line of a block's content? I am referring to the visual line determined by the browser, not the line seen in the source code. ...

"SyntaxError: import statements can only be at the top level of a module" is the error message that I keep encountering.`

For the complete code, click here: https://github.com/vscodr/axios_issue After spending some time away from JavaScript working in Python, I decided to come back and try to tackle similar tasks using JS. However, I seem to be stuck at a very basic issue! D ...

Switch effortlessly between one animation and another with Angular.js

I have two animations named "prev" and "next". Upon clicking the prev button, the "prev" animation should play. Similarly, when you click on the "next" button, the "next" animation should be triggered. I am using ng-class to achieve this behavior. How can ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

What causes the element to remain visible despite the changes made to the v-show attribute?

<!DOCTYPE html> <html> <head> <title>test</title> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <p v-show="show&qu ...

What causes TypeScript generics to infer varying types when an array member is enveloped?

I'm having trouble finding an answer to this potentially duplicate question, so please redirect me if it has already been addressed. My experience with generics in TypeScript has shown me that the inferred types can vary based on whether a generic is ...

Having Trouble with Your Instafeed Script

I've been working on a project that involves integrating an Instagram feed into a website. However, I'm facing difficulties getting it to function properly. Here's the code that I have implemented. <script type="text/javascript"> ...

Modify the CSS to update the navbar's active color

I'm currently using a simple CSS top navbar (without Bootstrap or any other framework) and I want to be able to change the active page's button color. For example, when I navigate to the home page, I want the button in the navbar to turn red or a ...

Creating a hierarchical list structure from a one-dimensional list using parent and child relationships in JavaScript

I am in the process of developing a web application that requires handling nested geographical data for display in a treeview and search functionality. The initial raw data structure resembles this: id:1, name:UK id:2: name: South-East, parentId: 1 id:3: ...

Accessing variables within a JSON string using the Request module in the Firefox Add-on SDK

I am facing an issue with my PHP script on the server. The script retrieves variables from the database and returns a JSON string containing image URLs. Here is a sample of the JSON string: [ { 'src':'imageurl1'} , { 'src':&a ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

Switching colors after uncovering text using JavaScript

I'm striving to achieve specific results with my code, but I'm having trouble pinpointing what exactly I'm doing wrong. Any guidance on how to correct my approach would be greatly appreciated. Currently, I've created rows that can be c ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...