{% extends 'base.html' %}
{% block head %}
<title>Task Master</title>
{% endblock %}
{% block body %}
<div class="content">
<h1>Task Master</h1>
{% if tasks|length < 1 %}
<h4 style="text-align: center">There are no tasks. Create one below!</h4>
{% else %}
<table class="center">
<tr>
<th>Task</th>
<th>Added</th>
<th>Action</th>
</tr>
{% for task in tasks %}
<tr>
<td> {{ task.content }}</td>
<td> {{ task.date_created.date()}}</td>
<td>
<a href="/delete/{{task.id}}">Delete</a>
<br>
<a href="/update/{{task.id}}">Update</a>
</td>
</tr>
{% endfor %}
</table>
{% endif %}
<hr width="100%">
<form action="/" method="post">
<input type="text" name="content" id="content"></input>
<input type="submit" value="Add Task"></input>
</form>
</div>
{% endblock %}
如果我理解正确,您希望阻止用户创建没有内容的任务。
要实现此目的,可以向内容的输入字段添加
required
属性。这样,在用户输入信息之前,不会发送表单。flash(...)
命令输出消息。
下面是一个示例应用程序,如果用户输入错误,他们会收到一条消息。
from datetime import datetime
from flask import (
Flask,
flash,
redirect,
render_template,
request,
url_for
)
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY='your secret here',
SQLALCHEMY_DATABASE_URI='sqlite:///example.db'
)
db = SQLAlchemy(app, model_class=Base)
class Task(db.Model):
id: db.Mapped[int] = db.mapped_column(db.Integer, primary_key=True)
content: db.Mapped[str] = db.mapped_column(db.String(), nullable=False)
date_created: db.Mapped[datetime] = db.mapped_column(
db.DateTime(timezone=True),
nullable=False,
server_default=func.now()
)
with app.app_context():
db.drop_all()
db.create_all()
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
content = request.form.get('content', '').strip()
if not content:
flash('Please provide content when creating a task.')
return redirect(request.url)
task = Task(content=content)
db.session.add(task)
db.session.commit()
return redirect(url_for('.index'))
stmt = db.select(Task)
tasks = db.session.execute(stmt).scalars().all()
return render_template('index.html', **locals())
# ...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Task Master</title>
</head>
<body>
<div class="content">
<h1>Task Master</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for category, message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="post">
<input type="text" name="content" id="content" required />
<input type="submit" value="Add Task" />
</form>
<hr/>
{% if tasks %}
<table class="center">
<tr>
<th>Task</th>
<th>Added</th>
<!-- ... -->
</tr>
{% for task in tasks %}
<tr>
<td> {{ task.content }}</td>
<td> {{ task.date_created.date()}}</td>
<!-- ... -->
</tr>
{% endfor %}
</table>
{% else %}
<h4 style="text-align: center">There are currently no tasks.</h4>
{% endif %}
</div>
</body>
</html>