Home > OS >  Trying to receive data using Python Flask Wtform but not working
Trying to receive data using Python Flask Wtform but not working

Time:04-20

I am learning Python, Flask and WTForm. What I aim for is that after I enter the email and password as required on the "/login" HTML page, and click the "Log In" button as defined in the CommentForm class, the page will be navigated to "success" or "denied" page. However, the code isn't working. After I click the button, the page stays still, instead of navigating to a different page. Does anything go awry regarding the code below? Thanks.

in main.py ⬇️

class CommentForm(FlaskForm):
    email = StringField(label="Email", validators=[Email()])
    password = PasswordField(label="Password", validators=[DataRequired(), Length(min=8)])
    submit = SubmitField(label="Log In")
    recaptcha = RecaptchaField()


@app.route("/login", methods=['GET', 'POST'])
def login():
    form = CommentForm(request.form)
    if request.method == 'POST' and form.validate():
        if form.email.data == "[email protected]" and form.password.data == "12345678":
            return render_template("success.html")
        else:
            return render_template("denied.html")
    return render_template("login.html", form=form)

in login.html ⬇️

<form method="post" action="{{ url_for('login') }}">
    {{ form.csrf_token }}
    {{ form.email.label }}<br>
    {{ form.email(rows=1, cols=30) }}
    {% for err in form.email.errors %}
        <span style="color:red">{{err}}</span>
    {% endfor %}<br>

     {{ form.password.label }}<br>
     {{ form.password(rows=1, cols=30) }}
     {% for err in form.password.errors %}
        <span style="color:red">{{err}}</span>
    {% endfor %}<br>

    {{form.submit}}
 </form>

CodePudding user response:

I tried to run your code (and as well tried some changes)

Python


@app.route("/login", methods=['GET', 'POST'])
def login():
  if request.method == "GET":
    form = CommentForm(request.form)
    return render_template("login.html", form = form)
  elif request.method == 'POST':
    form = CommentForm(request.form)
    if form.validate_on_submit():
      if form.email.data == "[email protected]" and form.password.data == "12345678":
          return "Welcome User"
    elif not form.validate_on_submit():
      print(form.errors)
      return "Hey it is invalid"
  return "??"

This results to the elif being called with an error of

{'recaptcha': ['The response parameter is missing.']}

To solve this

  1. Add {{form.recaptcha}} on your login.html

  2. Go to https://www.google.com/recaptcha/admin/create

  3. Fill up the form and get a public and private key

  4. On your flask application set

app.config["RECAPTCHA_PUBLIC_KEY"] = "yourkey"
app.config["RECAPTCHA_PRIVATE_KEY"] = "yourkey"
  • Related