wtforms will not return form.validate() as true [duplicate]Form is never valid with WTFormsReturn JSON response from Flask viewwtforms, CSRF, flask, FieldListMultiple forms in a single page using flask and WTFormsWTForms BooleanField treats JSON false value as truechained selectfield in wtforms FlaskFlask-WTForms form.validate() fails on dynamic choicesWtforms custom validation message ignoredHow to enter a list in WTForms?Active character count of wtforms TextAreaField

writing a function between sets vertically

how to find which software is doing ssh connection?

A medieval book with a redhead girl as a main character who allies with vampires and werewolves against scientific opposition

Should I email my professor to clear up a (possibly very irrelevant) awkward misunderstanding?

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

My student in one course asks for paid tutoring in another course. Appropriate?

How to address players struggling with simple controls?

How could I create a situation in which a PC has to make a saving throw or be forced to pet a dog?

Got a new frameset, don't know why I need this split ring collar?

How do I correctly reduce geometry on part of a mesh?

What kind of chart is this?

What is the context for Napoleon's quote "[the Austrians] did not know the value of five minutes"?

What is this plant I saw for sale at a Romanian farmer's market?

Boundaries and Buddhism

How to prevent cables getting intertwined

Is a sequel allowed to start before the end of the first book?

Expand command in an argument before the main command

What is the precise meaning of "подсел на мак"?

You may find me... puzzling

Do battery electrons only move if there is a positive terminal at the end of the wire?

Fantasy game inventory — Ch. 5 Automate the Boring Stuff

Explicit song lyrics checker

First occurrence in the Sixers sequence

Does cooling a potato change the nature of its carbohydrates?



wtforms will not return form.validate() as true [duplicate]


Form is never valid with WTFormsReturn JSON response from Flask viewwtforms, CSRF, flask, FieldListMultiple forms in a single page using flask and WTFormsWTForms BooleanField treats JSON false value as truechained selectfield in wtforms FlaskFlask-WTForms form.validate() fails on dynamic choicesWtforms custom validation message ignoredHow to enter a list in WTForms?Active character count of wtforms TextAreaField






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1
















This question already has an answer here:



  • Form is never valid with WTForms

    1 answer



I'm trying to validate inputs for a contact form loosely following Lalith Polepeddi's tutorial. I have used this tutorial before with slight adjustments, but this time the inputs will not validate no matter what I try.



if form.validate() in my routes.py always returns false. I uploaded the (entire venv to github with only the offending code)https://github.com/1988mazdab2000/wtfwtf.git



forms.py file:




class ContactForm(Form):
name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")


my routes.py file:



from flask import render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail

mail = Mail()

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()

if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)

return render_template('contact.html', success=True)

elif request.method == 'GET':
return render_template('contact.html', form=form)


any help with this would be greatly appreciated. I have used identical code to do this in the last three months and I'm stuck.



I've tried using different validators and started with a fresh install of raspbian on two different Pis.



I'd like for the form validators to work properly.










share|improve this question















marked as duplicate by davidism flask
Users with the  flask badge can single-handedly close flask questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 25 at 14:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • your GitHub link is not working

    – Harun-Ur-Rashid
    Mar 25 at 5:19











  • Fixed, sorry about that

    – dayot538
    Mar 25 at 5:31











  • did you check validate_on_submit ?

    – VillageMonkey
    Mar 25 at 5:50

















-1
















This question already has an answer here:



  • Form is never valid with WTForms

    1 answer



I'm trying to validate inputs for a contact form loosely following Lalith Polepeddi's tutorial. I have used this tutorial before with slight adjustments, but this time the inputs will not validate no matter what I try.



if form.validate() in my routes.py always returns false. I uploaded the (entire venv to github with only the offending code)https://github.com/1988mazdab2000/wtfwtf.git



forms.py file:




class ContactForm(Form):
name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")


my routes.py file:



from flask import render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail

mail = Mail()

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()

if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)

return render_template('contact.html', success=True)

elif request.method == 'GET':
return render_template('contact.html', form=form)


any help with this would be greatly appreciated. I have used identical code to do this in the last three months and I'm stuck.



I've tried using different validators and started with a fresh install of raspbian on two different Pis.



I'd like for the form validators to work properly.










share|improve this question















marked as duplicate by davidism flask
Users with the  flask badge can single-handedly close flask questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 25 at 14:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


















  • your GitHub link is not working

    – Harun-Ur-Rashid
    Mar 25 at 5:19











  • Fixed, sorry about that

    – dayot538
    Mar 25 at 5:31











  • did you check validate_on_submit ?

    – VillageMonkey
    Mar 25 at 5:50













-1












-1








-1









This question already has an answer here:



  • Form is never valid with WTForms

    1 answer



I'm trying to validate inputs for a contact form loosely following Lalith Polepeddi's tutorial. I have used this tutorial before with slight adjustments, but this time the inputs will not validate no matter what I try.



if form.validate() in my routes.py always returns false. I uploaded the (entire venv to github with only the offending code)https://github.com/1988mazdab2000/wtfwtf.git



forms.py file:




class ContactForm(Form):
name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")


my routes.py file:



from flask import render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail

mail = Mail()

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()

if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)

return render_template('contact.html', success=True)

elif request.method == 'GET':
return render_template('contact.html', form=form)


any help with this would be greatly appreciated. I have used identical code to do this in the last three months and I'm stuck.



I've tried using different validators and started with a fresh install of raspbian on two different Pis.



I'd like for the form validators to work properly.










share|improve this question

















This question already has an answer here:



  • Form is never valid with WTForms

    1 answer



I'm trying to validate inputs for a contact form loosely following Lalith Polepeddi's tutorial. I have used this tutorial before with slight adjustments, but this time the inputs will not validate no matter what I try.



if form.validate() in my routes.py always returns false. I uploaded the (entire venv to github with only the offending code)https://github.com/1988mazdab2000/wtfwtf.git



forms.py file:




class ContactForm(Form):
name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
subject = TextField("Subject", [validators.Required("Please enter a subject.")])
message = TextAreaField("Message", [validators.Required("Please enter a message.")])
submit = SubmitField("Send")


my routes.py file:



from flask import render_template, request, flash
from forms import ContactForm
from flask_mail import Message, Mail

mail = Mail()

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()

if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
msg.body = """
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)

return render_template('contact.html', success=True)

elif request.method == 'GET':
return render_template('contact.html', form=form)


any help with this would be greatly appreciated. I have used identical code to do this in the last three months and I'm stuck.



I've tried using different validators and started with a fresh install of raspbian on two different Pis.



I'd like for the form validators to work properly.





This question already has an answer here:



  • Form is never valid with WTForms

    1 answer







flask flask-wtforms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 5:29







dayot538

















asked Mar 25 at 4:56









dayot538dayot538

11




11




marked as duplicate by davidism flask
Users with the  flask badge can single-handedly close flask questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 25 at 14:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by davidism flask
Users with the  flask badge can single-handedly close flask questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 25 at 14:04


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • your GitHub link is not working

    – Harun-Ur-Rashid
    Mar 25 at 5:19











  • Fixed, sorry about that

    – dayot538
    Mar 25 at 5:31











  • did you check validate_on_submit ?

    – VillageMonkey
    Mar 25 at 5:50

















  • your GitHub link is not working

    – Harun-Ur-Rashid
    Mar 25 at 5:19











  • Fixed, sorry about that

    – dayot538
    Mar 25 at 5:31











  • did you check validate_on_submit ?

    – VillageMonkey
    Mar 25 at 5:50
















your GitHub link is not working

– Harun-Ur-Rashid
Mar 25 at 5:19





your GitHub link is not working

– Harun-Ur-Rashid
Mar 25 at 5:19













Fixed, sorry about that

– dayot538
Mar 25 at 5:31





Fixed, sorry about that

– dayot538
Mar 25 at 5:31













did you check validate_on_submit ?

– VillageMonkey
Mar 25 at 5:50





did you check validate_on_submit ?

– VillageMonkey
Mar 25 at 5:50












2 Answers
2






active

oldest

votes


















0














As @VillageMonkey said, use validate_on_submit. More can be found in official documentation.



Here is an example of using form validation using Flask-WTF. In this example, the login form requires a valid email address and a password with at least 6 and at most 35 characters long.



app.py:



from flask import render_template, url_for, request, redirect, flash, Flask
from forms import LoginForm

app = Flask(__name__)
app.secret_key = 'secret key'

@app.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if request.method == 'POST':
if form.validate_on_submit() == False:
flash('Form validation failed')
return render_template('login.html', form=form)
user_email = form.email.data
user_password = form.password.data
if user_email and user_password:
return " - ".format(user_email, user_password)
return render_template('login.html', form=form)

if __name__ == '__main__':
app.run(debug=True)


forms.py:



from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo

class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
submit = SubmitField('Login')


login.html:



<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
% with messages = get_flashed_messages() %
% if messages %
<ul class=flashes>
% for message in messages %
<li> message </li>
% endfor %
</ul>
% endif %
% endwith %
<form method="POST" action="">
form.csrf_token
<div>
form.email.label form.email
% if form.email.errors %
<ul style="color: red;">
% for error in form.email.errors %
<li> error </li>
% endfor %
</ul>
% endif %
</div>
<div>
form.password.label form.password
% if form.password.errors %
<ul style="color: red;">
% for error in form.password.errors %
<li> error </li>
% endfor %
</ul>
% endif %
</div>
<div>
form.submit
</div>
</form>

</body>
</html>


Directory structure:



.
├── app.py
├── forms.py
└── templates
└── login.html


requirements.txt:



Click==7.0
Flask==1.0.2
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.1
Werkzeug==0.15.0
WTForms==2.2.1


Output:



Get request of login route:



login form



Post request of login route (failed validation):



failed validation



Post request of login route (after successful validation):



validated response






share|improve this answer






























    0














    In the template use form.hidden_tag() for csrf protection.



    <form action=" url_for('contact') " method="post">

    form.hidden_tag()
    </form>





    share|improve this answer































      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      As @VillageMonkey said, use validate_on_submit. More can be found in official documentation.



      Here is an example of using form validation using Flask-WTF. In this example, the login form requires a valid email address and a password with at least 6 and at most 35 characters long.



      app.py:



      from flask import render_template, url_for, request, redirect, flash, Flask
      from forms import LoginForm

      app = Flask(__name__)
      app.secret_key = 'secret key'

      @app.route("/login", methods=['GET', 'POST'])
      def login():
      form = LoginForm()
      if request.method == 'POST':
      if form.validate_on_submit() == False:
      flash('Form validation failed')
      return render_template('login.html', form=form)
      user_email = form.email.data
      user_password = form.password.data
      if user_email and user_password:
      return " - ".format(user_email, user_password)
      return render_template('login.html', form=form)

      if __name__ == '__main__':
      app.run(debug=True)


      forms.py:



      from flask_wtf import FlaskForm
      from wtforms import StringField, PasswordField, SubmitField, BooleanField
      from wtforms.validators import DataRequired, Length, Email, EqualTo

      class LoginForm(FlaskForm):
      email = StringField('Email', validators=[DataRequired(), Email()])
      password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
      submit = SubmitField('Login')


      login.html:



      <!DOCTYPE html>
      <html>
      <head>
      <title>Login</title>
      </head>
      <body>
      % with messages = get_flashed_messages() %
      % if messages %
      <ul class=flashes>
      % for message in messages %
      <li> message </li>
      % endfor %
      </ul>
      % endif %
      % endwith %
      <form method="POST" action="">
      form.csrf_token
      <div>
      form.email.label form.email
      % if form.email.errors %
      <ul style="color: red;">
      % for error in form.email.errors %
      <li> error </li>
      % endfor %
      </ul>
      % endif %
      </div>
      <div>
      form.password.label form.password
      % if form.password.errors %
      <ul style="color: red;">
      % for error in form.password.errors %
      <li> error </li>
      % endfor %
      </ul>
      % endif %
      </div>
      <div>
      form.submit
      </div>
      </form>

      </body>
      </html>


      Directory structure:



      .
      ├── app.py
      ├── forms.py
      └── templates
      └── login.html


      requirements.txt:



      Click==7.0
      Flask==1.0.2
      Flask-WTF==0.14.2
      itsdangerous==1.1.0
      Jinja2==2.10
      MarkupSafe==1.1.1
      Werkzeug==0.15.0
      WTForms==2.2.1


      Output:



      Get request of login route:



      login form



      Post request of login route (failed validation):



      failed validation



      Post request of login route (after successful validation):



      validated response






      share|improve this answer



























        0














        As @VillageMonkey said, use validate_on_submit. More can be found in official documentation.



        Here is an example of using form validation using Flask-WTF. In this example, the login form requires a valid email address and a password with at least 6 and at most 35 characters long.



        app.py:



        from flask import render_template, url_for, request, redirect, flash, Flask
        from forms import LoginForm

        app = Flask(__name__)
        app.secret_key = 'secret key'

        @app.route("/login", methods=['GET', 'POST'])
        def login():
        form = LoginForm()
        if request.method == 'POST':
        if form.validate_on_submit() == False:
        flash('Form validation failed')
        return render_template('login.html', form=form)
        user_email = form.email.data
        user_password = form.password.data
        if user_email and user_password:
        return " - ".format(user_email, user_password)
        return render_template('login.html', form=form)

        if __name__ == '__main__':
        app.run(debug=True)


        forms.py:



        from flask_wtf import FlaskForm
        from wtforms import StringField, PasswordField, SubmitField, BooleanField
        from wtforms.validators import DataRequired, Length, Email, EqualTo

        class LoginForm(FlaskForm):
        email = StringField('Email', validators=[DataRequired(), Email()])
        password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
        submit = SubmitField('Login')


        login.html:



        <!DOCTYPE html>
        <html>
        <head>
        <title>Login</title>
        </head>
        <body>
        % with messages = get_flashed_messages() %
        % if messages %
        <ul class=flashes>
        % for message in messages %
        <li> message </li>
        % endfor %
        </ul>
        % endif %
        % endwith %
        <form method="POST" action="">
        form.csrf_token
        <div>
        form.email.label form.email
        % if form.email.errors %
        <ul style="color: red;">
        % for error in form.email.errors %
        <li> error </li>
        % endfor %
        </ul>
        % endif %
        </div>
        <div>
        form.password.label form.password
        % if form.password.errors %
        <ul style="color: red;">
        % for error in form.password.errors %
        <li> error </li>
        % endfor %
        </ul>
        % endif %
        </div>
        <div>
        form.submit
        </div>
        </form>

        </body>
        </html>


        Directory structure:



        .
        ├── app.py
        ├── forms.py
        └── templates
        └── login.html


        requirements.txt:



        Click==7.0
        Flask==1.0.2
        Flask-WTF==0.14.2
        itsdangerous==1.1.0
        Jinja2==2.10
        MarkupSafe==1.1.1
        Werkzeug==0.15.0
        WTForms==2.2.1


        Output:



        Get request of login route:



        login form



        Post request of login route (failed validation):



        failed validation



        Post request of login route (after successful validation):



        validated response






        share|improve this answer

























          0












          0








          0







          As @VillageMonkey said, use validate_on_submit. More can be found in official documentation.



          Here is an example of using form validation using Flask-WTF. In this example, the login form requires a valid email address and a password with at least 6 and at most 35 characters long.



          app.py:



          from flask import render_template, url_for, request, redirect, flash, Flask
          from forms import LoginForm

          app = Flask(__name__)
          app.secret_key = 'secret key'

          @app.route("/login", methods=['GET', 'POST'])
          def login():
          form = LoginForm()
          if request.method == 'POST':
          if form.validate_on_submit() == False:
          flash('Form validation failed')
          return render_template('login.html', form=form)
          user_email = form.email.data
          user_password = form.password.data
          if user_email and user_password:
          return " - ".format(user_email, user_password)
          return render_template('login.html', form=form)

          if __name__ == '__main__':
          app.run(debug=True)


          forms.py:



          from flask_wtf import FlaskForm
          from wtforms import StringField, PasswordField, SubmitField, BooleanField
          from wtforms.validators import DataRequired, Length, Email, EqualTo

          class LoginForm(FlaskForm):
          email = StringField('Email', validators=[DataRequired(), Email()])
          password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
          submit = SubmitField('Login')


          login.html:



          <!DOCTYPE html>
          <html>
          <head>
          <title>Login</title>
          </head>
          <body>
          % with messages = get_flashed_messages() %
          % if messages %
          <ul class=flashes>
          % for message in messages %
          <li> message </li>
          % endfor %
          </ul>
          % endif %
          % endwith %
          <form method="POST" action="">
          form.csrf_token
          <div>
          form.email.label form.email
          % if form.email.errors %
          <ul style="color: red;">
          % for error in form.email.errors %
          <li> error </li>
          % endfor %
          </ul>
          % endif %
          </div>
          <div>
          form.password.label form.password
          % if form.password.errors %
          <ul style="color: red;">
          % for error in form.password.errors %
          <li> error </li>
          % endfor %
          </ul>
          % endif %
          </div>
          <div>
          form.submit
          </div>
          </form>

          </body>
          </html>


          Directory structure:



          .
          ├── app.py
          ├── forms.py
          └── templates
          └── login.html


          requirements.txt:



          Click==7.0
          Flask==1.0.2
          Flask-WTF==0.14.2
          itsdangerous==1.1.0
          Jinja2==2.10
          MarkupSafe==1.1.1
          Werkzeug==0.15.0
          WTForms==2.2.1


          Output:



          Get request of login route:



          login form



          Post request of login route (failed validation):



          failed validation



          Post request of login route (after successful validation):



          validated response






          share|improve this answer













          As @VillageMonkey said, use validate_on_submit. More can be found in official documentation.



          Here is an example of using form validation using Flask-WTF. In this example, the login form requires a valid email address and a password with at least 6 and at most 35 characters long.



          app.py:



          from flask import render_template, url_for, request, redirect, flash, Flask
          from forms import LoginForm

          app = Flask(__name__)
          app.secret_key = 'secret key'

          @app.route("/login", methods=['GET', 'POST'])
          def login():
          form = LoginForm()
          if request.method == 'POST':
          if form.validate_on_submit() == False:
          flash('Form validation failed')
          return render_template('login.html', form=form)
          user_email = form.email.data
          user_password = form.password.data
          if user_email and user_password:
          return " - ".format(user_email, user_password)
          return render_template('login.html', form=form)

          if __name__ == '__main__':
          app.run(debug=True)


          forms.py:



          from flask_wtf import FlaskForm
          from wtforms import StringField, PasswordField, SubmitField, BooleanField
          from wtforms.validators import DataRequired, Length, Email, EqualTo

          class LoginForm(FlaskForm):
          email = StringField('Email', validators=[DataRequired(), Email()])
          password = PasswordField('Password', validators=[DataRequired(), Length(min=6, max=35)])
          submit = SubmitField('Login')


          login.html:



          <!DOCTYPE html>
          <html>
          <head>
          <title>Login</title>
          </head>
          <body>
          % with messages = get_flashed_messages() %
          % if messages %
          <ul class=flashes>
          % for message in messages %
          <li> message </li>
          % endfor %
          </ul>
          % endif %
          % endwith %
          <form method="POST" action="">
          form.csrf_token
          <div>
          form.email.label form.email
          % if form.email.errors %
          <ul style="color: red;">
          % for error in form.email.errors %
          <li> error </li>
          % endfor %
          </ul>
          % endif %
          </div>
          <div>
          form.password.label form.password
          % if form.password.errors %
          <ul style="color: red;">
          % for error in form.password.errors %
          <li> error </li>
          % endfor %
          </ul>
          % endif %
          </div>
          <div>
          form.submit
          </div>
          </form>

          </body>
          </html>


          Directory structure:



          .
          ├── app.py
          ├── forms.py
          └── templates
          └── login.html


          requirements.txt:



          Click==7.0
          Flask==1.0.2
          Flask-WTF==0.14.2
          itsdangerous==1.1.0
          Jinja2==2.10
          MarkupSafe==1.1.1
          Werkzeug==0.15.0
          WTForms==2.2.1


          Output:



          Get request of login route:



          login form



          Post request of login route (failed validation):



          failed validation



          Post request of login route (after successful validation):



          validated response







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 25 at 6:41









          arshoarsho

          4,63821838




          4,63821838























              0














              In the template use form.hidden_tag() for csrf protection.



              <form action=" url_for('contact') " method="post">

              form.hidden_tag()
              </form>





              share|improve this answer





























                0














                In the template use form.hidden_tag() for csrf protection.



                <form action=" url_for('contact') " method="post">

                form.hidden_tag()
                </form>





                share|improve this answer



























                  0












                  0








                  0







                  In the template use form.hidden_tag() for csrf protection.



                  <form action=" url_for('contact') " method="post">

                  form.hidden_tag()
                  </form>





                  share|improve this answer















                  In the template use form.hidden_tag() for csrf protection.



                  <form action=" url_for('contact') " method="post">

                  form.hidden_tag()
                  </form>






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 26 at 5:06

























                  answered Mar 25 at 6:21









                  VillageMonkeyVillageMonkey

                  968




                  968













                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript