Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRastko Jovic
14,883 PointsFLASK: Form Validation not working!
I am trying to return a success message upon form validation but it doesn't work! Here is the code:
app.py
@app.route('/', methods=['GET','POST'])
def index():
signin_form = forms.SignInForm()
if signin_form.validate_on_submit():
return 'Form validated!'
# If form not validated properly do this...
return render_template('index.html', signin_form=signin_form)
forms.py
class SignInForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
macro.html
{% macro render_field(field) %}
{{ field.label }}
<input type="text" name="{{ field.label.text.lower() }}" id = "{{ field.label.text.lower() }}">
{% if field.errors %}
{% for error in field.errors %}
<p class="error">{{ error }}</p>
{% endfor %}
{% endif %}
{% endmacro %}
index.html
<body>
<!-- Log In Form-->
<form action="" method="POST" name="signin_form">
<h3>Sign In</h3>
{{ render_field(signin_form.username) }}<br>
{{ render_field(signin_form.password) }}
<input type="submit" value="Sign In">
</form>
</form>
</body>
2 Answers
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsI have always used the Form class rather than FlaskForm. Not sure, may be someone else would know the difference between the two.
below is an example of one of my forms.
from flask_wtf import Form
from wtforms import StringField, PasswordField,TextAreaField
from wtforms.validators import (DataRequired, Regexp, ValidationError, Email,
Length, EqualTo)
class LoginForm(Form):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Rastko
class SignInForm(Form): # i think here it should be Form rather than FlaskForm
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
Rastko Jovic
14,883 PointsIn the flask_wtf documentation an example is shown:
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
https://flask-wtf.readthedocs.io/en/stable/quickstart.html#creating-forms