Search code examples
pythonflaskreturnresponsevalueerror

ValueError, even if the logic is the same with other codes


I have a problem with view functions. My other codes is properly working and have the same structure or logic. I am just wondering why in this case it's not working when the logic is the same with the rest, while the rest is properly working, this one is getting an error.

# ########### POST answers ###############################
        if request.method == 'POST':
            if form.validate_on_submit():
                answer = request.form['answer_text']
                name = form.name.data
                subject = request.form['hidden_sub']
                flash('Homework posted for ' + str(subject) + "!")
                try:
                    cur = mysql.connection.cursor()
                    sql = '''INSERT INTO answers (email, school, name, answer, subject) 
                            VALUES (%s, %s, %s, %s, %s)'''
                    cur.execute(sql, (session['user'], session['school'], name, answer, subject))
                    mysql.connection.commit()
                finally:
                    cur = mysql.connection.cursor()
                    cur.close()
                    return render_template('s_homework.html', user=session['user'], school=session['school'],
                                       classes=classes, infos=infos, info_size=info_size, form=form)


HTML FORM:
    <form method="POST" action="/s_homework/{{user}}/{{school}}/">
           <input type="text" value="{{sub}}" style="visibility:hidden;" name="hidden_sub">
           {{ wtf.form_field(form.name) }}
           <label> Answer Form*</label>
           <textarea class="form-control" name="answer_text" style="height:10em;"></textarea>
           <p> </p>
           {{ wtf.form_field(form.submit, class="btn btn-success",
             style="position:relative; left:88%;") }}
</form>

Solution

  • The problem must be that you have a return in the case of

        if form.validate_on_submit():
    

    But not a return for the "else" case (which was not covered). With the flask functions, you always have to return something. You should return the template, but flash "Error with your form." There might also be something wrong with your form, but I can't tell that from the code.