I'm building a basic flask todo list web application, with main app.py
and 4 html pages, add.html
, edit.html
, home.html
, todos.html
.
Everything works perfectly fine, except when "add todo" button is clicked on the main page, I have this error 404:
Here's my app.py:
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(200), nullable=False)
status = db.Column(db.String(20), nullable=False, default='Incomplete')
@app.route('/')
def home():
return render_template('home.html')
@app.route('/add', methods=['GET', 'POST'])
def add_todo():
if request.method == 'POST':
description = request.form['description']
new_todo = Todo(description=description)
db.session.add(new_todo)
db.session.commit()
return redirect(url_for('todos'))
return render_template('add.html')
@app.route('/todos')
def todos():
todos = Todo.query.order_by(Todo.status, Todo.id).all()
return render_template('todos.html', todos=todos)
@app.route('/todos/mark_complete/<int:todo_id>')
def mark_complete(todo_id):
todo = Todo.query.get_or_404(todo_id)
todo.status = 'Completed'
db.session.commit()
return redirect(url_for('todos'))
@app.route('/todos/mark_incomplete/<int:todo_id>')
def mark_incomplete(todo_id):
todo = Todo.query.get_or_404(todo_id)
todo.status = 'Incomplete'
db.session.commit()
return redirect(url_for('todos'))
@app.route('/todos/edit/<int:todo_id>', methods=['GET', 'POST'])
def edit(todo_id):
todo = Todo.query.get_or_404(todo_id)
if request.method == 'POST':
todo.description = request.form['description']
db.session.commit()
return redirect(url_for('todos'))
return render_template('edit.html', todo=todo)
@app.route('/todos/delete/<int:todo_id>')
def delete(todo_id):
todo = Todo.query.get_or_404(todo_id)
db.session.delete(todo)
db.session.commit()
return redirect(url_for('todos'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run()
And here's my add.html:
<!DOCTYPE html>
<html>
<head>
<title>Add ToDo</title>
</head>
<body>
<h1>Add ToDo</h1>
<form method="POST" action="{{ url_for('add_todo') }}">
<label for="description">Description:</label>
<input type="text" id="description" name="description">
<input type="submit" value="Add">
</form>
</body>
</html>