我在complete.html
的Jinja2模板中有一个if语句,但无论if条件是True还是False,它都不会运行正确的代码。
我将重定向url调用到另一个视图函数,然后呈现它,携带确定if循环条件的变量。我打印出条件并且它是正确的,但是if循环没有运行正确的代码。我错过了导致if语句无法正常工作的内容。
我的代码:
view.py
@app.route('/', methods=['GET', 'POST'])
def home():
form = CourseForm()
if form.validate_on_submit():
course_name = form.cname.data.upper()
course_id = form.cid.data
course_sec = form.sec.data.upper()
email = form.email.data.lower()
reserved = form.reserved.data
result = checkCourse(course_name, course_id, course_sec)
if result is not None:
flash('Unable to find course')
else:
known = False
course = Course.query.filter_by(cname=course_name, cid=course_id, sec=course_sec).first()
if course is None:
course = Course(cname=course_name, cid=course_id, sec=course_sec)
db.session.add(course)
db.session.flush()
user = User(email=email, course_id=course.id, reserved=reserved)
db.session.add(user)
else:
ckey = course.id
result = checkUser(email, ckey, reserved)
if result != None:
known = True
else:
user = User(email=email, course_id=ckey, reserved=reserved)
db.session.add(user)
db.session.commit()
return redirect(url_for('complete', known=known))
return render_template('home.html', form=form)
@app.route('/complete')
def complete():
known = request.args.get('known', type=string)
app.logger.debug(known)
return render_template('complete.html', known=known)
模板:
base.html
{% extends "bootstrap/base.html" %}
{% block title %}UBC Course Alert{% endblock %}
{% block styles %}
{{super()}}
<link rel="stylesheet"
href="{{url_for('.static', filename='home.css')}}">
{% endblock %}
{% block content %}
<div class="jumbotron">
<div class="container">
{% block page_content %}{% endblock %}
</div>
</div>
{% endblock %}
complete.html
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block page_content %}
<p>
{% if known %}
You already added this course. You'll receive a email as soon as there's space :)
{% else %}
Thanks for registering your course, you'll receive a email as soon as there's space!
{% endif %}
</p>
{% endblock %}
答案 0 :(得分:1)
您将变量known
转换为字符串;它将包含字符串值'True'
或'False'
。这些是不是布尔值,而是4或5个字符长的字符串。然后两个字符串都被视为真值,因为它们是非空的。
您必须将字符串翻译为布尔值,或将known
值保留为空以指示错误值。
转换回布尔值就像:
known = request.args.get('known', type=string) == 'True'
使用 false 的空值时如下所示:
return redirect(url_for('complete', known='1' if known else ''))
和
known = request.args.get('known', default='', type=bool)