0
0

More than 1 year has passed since last update.

Flaskを使って簡単なtodolist appを作る

Posted at

app.py

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    task = db.Column(db.String(255))
    done = db.Column(db.Boolean, default=False)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        task = request.form['task']
        new_todo = Todo(task=task)
        db.session.add(new_todo)
        db.session.commit()

    todos = Todo.query.all()
    return render_template('index.html', todos=todos)

@app.route('/delete/<id>')
def delete(id):
    todo = Todo.query.get(id)
    db.session.delete(todo)
    db.session.commit()
    return redirect('/')

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>To-Do List</title>
</head>
<body>
    <h1>To-Do List</h1>
    <form action="/" method="post">
        <input type="text" name="task" placeholder="Add a new task">
        <input type="submit" value="Add">
    </form>
    <ul>
        {% for todo in todos %}
            <li>
                {{ todo.task }}
                <a href="/delete/{{ todo.id }}">Delete</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0