Delete Tasks using Django framework

Im currently creating a todo list project using the Django web framework and i currently have an issue with deleting tasks of the webpage. My issue is that i don’t know and can’t find suitable code to perform the action of deleting a task from the webpage. This is what the webpage looks like: todo list.

I believe my issue is contained in the views.py file:

from django.shortcuts import render, redirect
from django.contrib import messages as django_messages
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import RegisterForm, CreateTask
from .models import Task  # Import Task model

def home(request):
    if request.method == 'POST':
        form = CreateTask(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = CreateTask()
    
    tasks = Task.objects.all().order_by('-created_at')[:10]  # Query Task model correctly
    context = {
        'form': form,
        'tasks': tasks,
    }
    return render(request, "home.html", context)

def delete_task(request, id):
    task = Task.objects.get(id=id)
    task.delete()
    return redirect('home')

@login_required
def user_logout(request):
    auth_logout(request)
    django_messages.success(request, 'Logged out successfully')
    return redirect("introduction")  # Redirect to a valid URL name

def user_login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)

        if user is not None:
            auth_login(request, user)
            django_messages.success(request, 'Login successful')
            return redirect('home')  # Replace 'index' with your actual URL name
        else:
            django_messages.error(request, 'Login failed')
    return render(request, "login.html")

def register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            django_messages.success(request, 'Registration successful')
            return redirect('home')  # Replace 'index' with your actual URL name
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form})

@login_required
def delete_user(request, username):
    try:
        u = User.objects.get(username=username)
        u.delete()
        django_messages.success(request, "User is deleted")
    except User.DoesNotExist:
        django_messages.error(request, "User doesn't exist")
    except Exception as e:
        django_messages.error(request, f"Error deleting user: {e}")
    return redirect("introduction")  # Redirect to a valid URL name

def introduction(request):
    return render(request, 'introduction.html')

These are the files i also used to create the project

models.py:

from django.db import models

class Task(models.Model):
    subject = models.CharField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)
    description = models.CharField(max_length=50)

    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.subject} - ({self.created_at})"`

forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Task

class RegisterForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class CreateTask(forms.ModelForm):
    class Meta:
        model = Task
        fields = ['subject', 'description']

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path("login/", views.user_login, name="login"),
    path("logout/", views.user_logout, name="logout"),
    path("introduction/", views.introduction, name="introduction"),
    path("register/", views.register, name="register"),
    path("delete-user/<str:username>", views.delete_user, name="delete-user")
]

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List</title>
</head>
<body>
    <div class="container">
        <h1>Todo List</h1>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Post Task</button>
        </form>
        <ul>
            {% for task in tasks %}
                <li>{{ task.subject }} - {{ task.description }} (Created at: {{ task.created_at }})</li>
            {% empty %}
                <li>No tasks available</li>
            {% endfor %}
        </ul>
        <div class="user-settings">
            {% if user.is_authenticated %}
                <a class="link-logout" href="{% url 'logout' %}">Logout</a>
                <a class="link-delete" href="{% url 'delete-user' username=user.username %}">Delete Account</a>
            {% else %}
                <a class="link-login" href="{% url 'login' %}">Login</a>
            {% endif %}
        </div>
    </div>
</body>
</html>

The code I tried in the views.py file for deleting tasks was:

def delete_task(request, id):
    task = Task.objects.get(id=id)
    task.delete()
    return redirect('home')

But this code didn’t work so i am right now struggling with the code i should write to properly delete tasks from the webpage. Does anyone have any suggestions, tips, example code or solutions that can solve this problem?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật