'How to prevent a flask form from being cleared if an input is wrong
I have looked for many solutions for this issue but I have not found one specific to Flask, so I have a flask form and I use WTForms to validate the form. The form only returns values if all validations are met and displays a little error animation if the validation is not met, however every time I submit my form even if most of the inputs are correct and say for instance one is wrong it prevents the form from returning values and the annoying part is that the entire form is cleared and the values which were correct are removed. I want the values which were correct to stay and only the values which threw and error to be removed, how would I achieve this?
My code
Python
class ValueForm(FlaskForm):
homecost = StringField('homecost', validators=[InputRequired()])
addedcost = StringField('addedcost', validators=[InputRequired()])
@app.route("/webcalculator", methods=['GET', 'POST'])
def webcalculator():
form = ValueForm()
req = request.form
if form.validate_on_submit():
print('Form Passed')
homecost = req.get('homecost')
addedcost = req.get('addedcost')
print(f'Home Costs: {homecost}')
print(f'Added Costs: {addedcost}')
return redirect(request.url)
return render_template("webcalculator.html", form=form)
HTML
<div class="form-group">
<div class="form-group col-md-1">
<label for="homecost" id="homecostlabel">Home Cost</label>
<input type="number" class="form-control" id="homecost" placeholder="0" name="homecost">
{% for error in form.homecost.errors %}
<style>
#homecost { border-color: rgba(255, 0, 0, 0.8);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(255, 0, 0, 0.8);
outline: 0 none;}
</style>
{% endfor %}
</div>
<div class="form-group">
<div class="form-group col-md-1">
<label for="addedcost" id="addedcostlabel">Added Costs</label>
<input type="number" class="form-control" id="addedcost" placeholder="0" name="addedcost">
{% for error in form.addedcost.errors %}
<style>
#addedcost { border-color: rgba(255, 0, 0, 0.8);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(255, 0, 0, 0.8);
outline: 0 none;}
</style>
{% endfor %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|