我创建了一个CRUD烧瓶web应用程序,用于安排卡车预约。我有一个HTML表单,用户在其中输入开始和结束日期,网页会在数据库中显示该时间段内的约会。
对于用户只输入开始日期而不输入结束日期的情况,我希望将"结束日期"设置为2050-01-01,以便用户可以查看开始日期之后的所有约会。
我试图在index((视图函数中编写一个if语句,但我不知道正确的语法。以下是我在伪代码中尝试做的事情:
if the (end date).value.length = 0, then
end date = '2050-01-01'
else
search_date_end = request.args.get('end_date_filter')
app.py:
@app.route('/', methods=['GET', 'POST'])
def index():
search_date_start = request.args.get('start_date_filter')
search_date_end = request.args.get('end_date_filter')
appts = appts_db.query
.filter(appts_db.pickup_date.between(search_date_start, search_date_end))
.order_by(appts_db.pickup_date).all()
return render_template('index.html', appts=appts)
index.html:
<h3>Appointment List:</h3>
<table>
<tr>
<th>Carrier</th>
<th>Material</th>
<th>Pickup Date [YYYY-MM-DD]</th>
</tr>
{% for appt in appts %}
<tr>
<td>{{ appt.carrier }}</td>
<td>{{ appt.material }}</td>
<td>{{ appt.pickup_date }}</td>
</tr>
{% endfor %}
</table>
<form action="/" method="GET">
<label for="start_date_filter">Choose a start date:</label>
<input type="date" id="start_date_filter" name="start_date_filter"
min="2022-01-01"><br>
<label for="end_date_filter">Choose an end date:</label>
<input type="date" id="end_date_filter" name="end_date_filter"
min="2022-01-01"><br>
<input type="submit" value="Filter Appointments">
</form>
您正在get
处理来自request.args
dict的值。因此,如果密钥不存在,您将获得None
。在结束值上添加一个if/else
就足够了。
@app.route('/', methods=['GET', 'POST'])
def index():
search_date_start = request.args.get('start_date_filter')
search_date_end = request.args.get('end_date_filter')
if search_date_end is None: # open ended
query = (
appts_db.query
.filter(appts_db.pickup_date >= search_date_start)
.order_by(appts_db.pickup_date)
)
else: # close ended
query = (
appts_db.query
.filter(appts_db.pickup_date.between(search_date_start, search_date_end))
.order_by(appts_db.pickup_date)
)
return render_template('index.html', appts=query.all())
有了新样式的select
语句(>=1.4(,它变得更加简单,因为只需要更改filter
。
@app.route('/', methods=['GET', 'POST'])
def index():
search_date_start = request.args.get('start_date_filter')
search_date_end = request.args.get('end_date_filter')
stmt = select(appts_db).order_by(appts_db.pickup_date)
if search_date_end is None: # open ended
stmt = stmt.filter(appts_db.pickup_date >= search_date_start)
else: # close ended
stmt = stmt.filter(appts_db.pickup_date.between(search_date_start, search_date_end))
result = session.scalars(stmt)
return render_template('index.html', appts=result.all())