title: Flask login form inside Bootstrap modal - how to handle form errors?
body: <p>I've placed my login form inside a Bootstrap modal. If the form is valid it submits and the user is logged in, but I need a way to display validation errors/failed attempts inside the modal window.</p>
  
  <p>I've only worked with forms that were constrained to one view until now. In those cases I was able to pass the form to the template (<code>render_template('foo.html', form=form)</code> which rendered the fields and handled errors with a <a href="http://flask.pocoo.org/docs/0.12/patterns/wtforms/#forms-in-templates" rel="nofollow noreferrer">macro</a>.</p>
  
  <p>The login modal I'm trying to create sits in the layout view which every template inherits, but the login form isn't passed by every view so the macro can't be used.</p>
  
  <p>Form</p>
  
  <pre><code>class LoginForm(FlaskForm):
      username = StringField('Username', validators=[DataRequired()])
      password = PasswordField('Password', validators=[DataRequired()])
  </code></pre>
  
  <p>View</p>
  
  <pre><code>@app.route('/login', methods=['POST'])
  def login():
      form = forms.LoginForm()
      if form.validate_on_submit():
          try:
              user = models.User.get(models.User.username == form.username.data)
          except models.DoesNotExist:
              flash("Your username or password doesn't match")
          else:
              if check_password_hash(user.password, form.password.data):
                  login_user(user)
                  flash("You've been logged in!")
                  return redirect(url_for('index'))
              else:
                  flash("Your username or password doesn't match")
  </code></pre>
  
  <p>Relevant modal code from layout template</p>
  
  <pre><code>&lt;div class="modal-body"&gt;
      &lt;form method="post" action='{{ url_for("login") }}' name="LoginForm"&gt;
          &lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /&gt;
          &lt;div class="form-group"&gt;
              &lt;label for="username"&gt;Username&lt;/label&gt;
              &lt;input type="text" class="form-control" name="username" id="username" placeholder="Username"&gt;
          &lt;/div&gt;
          &lt;div class="form-group"&gt;
              &lt;label for="password"&gt;Password&lt;/label&gt;
              &lt;input type="password" class="form-control" name="password" placeholder="Password"&gt;&lt;/p&gt;
          &lt;/div&gt;
          &lt;p&gt;&lt;button type="submit" class="btn btn-primary"&gt;Sign in&lt;/button&gt;
              &lt;a href="#"&gt;Forgot Password?&lt;/a&gt;
          &lt;/p&gt;
      &lt;/form&gt;
  &lt;/div&gt;
  </code></pre>