نحوه حذف یک task

  • مدرس : علی بیگدلی
  • تاریخ انتشار: 1404/11/14
  • تعداد بازدید: 4

در این مرحله می‌خواهیم قابلیت حذف یک آیتم موجود در لیست Todo را اضافه کنیم. برای این کار یک مسیر جدید ایجاد می‌کنیم که آیتم مورد نظر را با استفاده از id پیدا کرده و از لیست حذف کند.

به‌روزرسانی app.py برای حذف

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# داده‌های اولیه بدون دیتابیس
todos = [
    {"id": 1, "task": "Learn Flask basics", "done": False},
    {"id": 2, "task": "Write first Flask app", "done": False},
    {"id": 3, "task": "Understand Jinja templates", "done": False}
]

@app.route("/")
def index():
    return render_template("index.html", todos=todos)

@app.route("/add", methods=["POST"])
def add_todo():
    new_task = request.form.get("task")
    if new_task:
        new_id = todos[-1]["id"] + 1 if todos else 1
        todos.append({"id": new_id, "task": new_task, "done": False})
    return redirect(url_for("index"))

@app.route("/edit/<int:todo_id>", methods=["GET", "POST"])
def edit_todo(todo_id):
    todo = next((item for item in todos if item["id"] == todo_id), None)
    if not todo:
        return redirect(url_for("index"))

    if request.method == "POST":
        todo["task"] = request.form.get("task")
        return redirect(url_for("index"))

    return render_template("edit.html", todo=todo)

# مسیر حذف آیتم
@app.route("/delete/<int:todo_id>")
def delete_todo(todo_id):
    global todos
    todos = [todo for todo in todos if todo["id"] != todo_id]
    return redirect(url_for("index"))

if __name__ == "__main__":
    app.run(debug=True)

به‌روزرسانی index.html برای اضافه کردن دکمه حذف

<!DOCTYPE html>
<html lang="fa">
<head>
    <meta charset="UTF-8">
    <title>Todo App</title>
</head>
<body>
    <h1>Todo List</h1>

    <form action="{{ url_for('add_todo') }}" method="post">
        <input type="text" name="task" placeholder="New task" required>
        <button type="submit">Add</button>
    </form>

    <ul>
        {% for todo in todos %}
        <li>
            {{ todo.task }}
            <a href="{{ url_for('edit_todo', todo_id=todo.id) }}">Edit</a>
            <a href="{{ url_for('delete_todo', todo_id=todo.id) }}">Delete</a>
        </li>
        {% endfor %}
    </ul>
</body>
</html>

حالا با کلیک روی لینک Delete کنار هر آیتم، آن آیتم از لیست حذف می‌شود و صفحه دوباره رفرش می‌شود.

در قدم بعدی می‌رویم سراغ جستجو بین آیتم‌ها (Search Todo).

ثبت دیدگاه


نکته: آدرس ایمیل شما منتشر نخواهد شد
0/600

دیدگاه کاربران (0)


هیچ دیدگاهی ثبت نشده است. می‌توانید اولین نفر باشید.