در این مرحله میخواهیم قابلیت ویرایش یک آیتم موجود در لیست Todo را اضافه کنیم. برای این کار یک مسیر جدید ایجاد میکنیم که فرم ویرایش را نمایش دهد و سپس با POST تغییرات را اعمال کنیم.
بهروزرسانی 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>")
def edit_todo_form(todo_id):
todo = next((item for item in todos if item["id"] == todo_id), None)
if not todo:
return redirect(url_for("index"))
return render_template("edit.html", todo=todo)
# مسیر اعمال تغییرات ویرایش
@app.route("/edit/<int:todo_id>", methods=["POST"])
def edit_todo(todo_id):
new_task = request.form.get("task")
for todo in todos:
if todo["id"] == todo_id:
todo["task"] = new_task
break
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(debug=True)
ایجاد فایل edit.html
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<title>Edit Todo</title>
</head>
<body>
<h1>Edit Todo</h1>
<form action="{{ url_for('edit_todo', todo_id=todo.id) }}" method="post">
<input type="text" name="task" value="{{ todo.task }}" required>
<button type="submit">Update</button>
</form>
<a href="{{ url_for('index') }}">Back to list</a>
</body>
</html>
حالا هر آیتم در لیست میتواند با رفتن به مسیر `/edit/
در قدم بعدی میرویم سراغ حذف آیتمها (Delete Todo).