Home > database >  flask template rendering weird
flask template rendering weird

Time:11-28

Looking at this, it should work right?

It seems like the get request is overwriting the post request return because it only renders no error.

Why is that?


index.html

{% if error %}
    <p>{{ error }}</p>
{% else %}
    <p>no error</p>
{% endif %}

main.py

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        post_data = request.get_json(force=True)
        if post_data['message'] == False:
            return render_template('index.html', error='not detected')
    return render_template('index.html')

CodePudding user response:

Look closely at post_data['message']. Are you absolutely sure it's False? If it's the string 'False', the code falls through and won't render an error.

CodePudding user response:

Try using else or elif.

else:

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        post_data = request.get_json(force=True)
        if post_data['message'] == False:
            return render_template('index.html', error='not detected')
    else:
        return render_template('index.html')

elif (recommended):

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        post_data = request.get_json(force=True)
        if post_data['message'] == False:
            return render_template('index.html', error='not detected')
    elif request.method == 'GET':
        return render_template('index.html')
  • Related