Removing data from a Django database using multiple forms within a single template

Just getting started with django and attempting to create a to-do list. I have successfully implemented functionality to change the color of an item from red to green when clicking on the "✓" button using JavaScript. However, I am now facing an issue with deleting objects from the Django database when clicking on the "X" button.

Here is the code I have so far:

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import *

def index(request):
    tasks = Task.objects.all()
    form = TaskForm()

    if request.method == "POST":
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect("/")
    context = {
        'tasks': tasks,
        'form': form
    }
    return render(request, "tasks/list.html", context)

def deletetask(request, pk):
    if request.method == "POST" and "delete" in request.POST:
        item = request.POST.get(id=pk)
        Task.objects.delete(id=item)
    return render(request, "tasks/list.html")

My forms.py:

from django import forms
from django.forms import ModelForm
from .models import *

class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = '__all__'

My models.py:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    complete = models.BooleanField(default=False)
    creted = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Template snippet:

<h3>Hello world from templates</h3>

<form action="/" method="POST"> {% csrf_token %}
    
    {{ form.title }}
    <input type="submit" name="Ajout medoc">
</form>


{% for task in tasks %}
    <div>
        <form action="/" method="POST">
        <p style="color: red" id="{{ task.id }}">
            <input type="button" name="cmd" value="✓" onclick="document.getElementById('{{ task.id }}').style.color = 'green'"> 
            
            <input type="button" name="delete" value="X" id="{{ task.id }}">
            
        {{ task }}
        </p>
        </form>
        
    </div>

{% endfor %}

Answer №1

If I were to approach this differently, I would make the following changes:

def remove_task(request, pk):
    instance = Task.objects.get(id=pk)
    instance.delete()
    
    return redirect('index')

Then, update your template with the following:

{% for task in tasks %}
<div >
    <p style="color: red" id="{{task.id}}">
        <input type="button" name="cmd" value="✓" onclick="document.getElementById('{{ task.id }}').style.color = 'green'"> 
        
        <a href="{% url 'remove_task' task.id %}">
             <button>X</button>
        </a>
        
    {{ task }}
    </p>
    
</div>

{% endfor %}

In your urls.py:

urlpatterns = [
   path("remove_task/", views.remove_task, name="remove_task"),

]

The code in the template is currently using a function within an "a" HTML tag instead of incorporating a form.

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

What is the process for fixing the top header row to display column titles in a bootstrap-vue table?

I am currently using a bootstrap-vue table with the following structure; https://i.sstatic.net/5sv6R.png Below is the code snippet for reference; <template> <div> <b-table hover :items="items"></b-table> </div ...

Is it possible to remove an element from a data structure in a web application using an HTTP command?

Apologies for the confusing title, I struggled to find a better way to describe it. Imagine sending a GET request to an API and receiving this data: { {id: 1, name: "John Doe", tags: ["Apple", "Orange", "Pear"]}, {id: 2, name: "Jane Doe", tags: [ ...

problem encountered when loading an HTML file within another HTML file using AJAX

By clicking a button, I successfully loaded a full HTML page (refer to the structure below) into another HTML page. <!--START:HTML to be loaded by ajax--> <head> <!--START: The content inside this head tag is not processed while the pag ...

Utilizing HighCharts in Your Project

View the graph here $(function () { var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'column', margin: [ 50, 50, 100, 80] ...

Fixed position of Material UI tooltip popper when the word length increases

https://i.sstatic.net/mXcqy.png I am striving to replicate the image above by customizing the MUI tooltip properties, but instead, I am only able to achieve this result: https://i.sstatic.net/Rr79x.png By applying a margin to the popper element, I was a ...

The Spring Boot and Angular Fusion Application

Currently, I am in the process of developing a Spring Boot Application with Angular as the frontend and Spring-Boot for the backend. My goal is to create a deployable war. After researching various resources online, my current understanding is that Spring ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Issue with navigation links on HTML website not functioning as expected

I would like the dropdown menu items to be clickable. For example: Menu item: Services Sub items: - branding } These already have working links - marketing } However, when I try to replace '#' with a link for Services, it d ...

Angular - service workers leading to unsuccessful uploads

When uploading files using Uppy (XHRUpload) in my Angular 6 app, the process is smooth on localhost with the service worker disabled. However, enabling the service worker results in successful uploads only for small files, while larger files fail to upload ...

Using WEBGL to Showcase Your Images: A Step-by-Step Guide

I'm hoping to effortlessly showcase an image on the canvas at specific x and y co-ordinates using WEBGL, but I'm unsure of the process. Must shaders be included along with all other technical details? I've come across code snippets for displ ...

How can you retrieve the input value in JavaScript when the cursor is not focused?

Here is an input I am working with: <a-form-item label="user" :colon="false"> <a-input placeholder="user" name="user" @keyup.enter="checkUser"/> </a-form-item> Within my methods: chec ...

Drag and release: Place within invalid drop areas

I'm currently developing a drag-and-drop web application using Vue.JS and Vuex Store. The drag-and-drop functionality is based on the HTML Drag and Drop API as outlined in the Mozilla documentation. I have successfully implemented the Dropzone Compone ...

How to troubleshoot Javascript code that fails to identify if a color is white

What could be causing my code to malfunction? I am attempting to determine if the paragraph text color is white (as determined by CSS settings). If it is indeed white, I want to change it to black for better visibility. function adjustColor() { if (d ...

Exploring the functionality of ISO 8601 periods with JavaScript

Has anyone successfully compared ISO 8601 periods in JavaScript to determine which period has a longer duration? For example, is P6M (6 months) longer than PT10M (10 minutes)? I haven't been able to find any built-in solutions for this. Any suggestio ...

Object property accessed using Javascript array syntax

Could you explain the inner workings of this process: https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/ How does JQuery configure foo[0] to trigger the get function? Upon inspecting the source code, I ...

Optimal method for file uploading with Node.js

How can I effectively manage file uploads in node js? I would like users to be able to upload profile images with the following specifications: -Validated size of at least 200 * 200 -Accepted file formats are png, jpg, jpeg, or gif -Additional functi ...

Establish a connection with a device using Node.js via UDP

I developed a TCP/IP device and successfully created a Python script to establish a connection and receive data. However, when attempting to replicate this functionality using Node.js, I encountered various challenges such as connection errors and security ...

Ways to determine if new data has been added to a MySQL table

Can anyone explain how the Facebook notification system operates? Here is my code snippet: (function retrieve_req() { $.ajax({ url: 'request_viewer_and_its_utilities.php', success: function(data) { $('.inte ...

Guide on looping through an array of objects and eliminating each item using JavaScript

someArray = [{name:"Ibrahim", cid:322}, {name:"Ismail", cid:423}]; Exploring this task further, I am seeking a reliable method to iterate over the array, perform certain actions, and eventually produce the desired output like so: someArray = []; This is ...