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 %}