My WebP imageCMSC388J
Flask

Forms

Learning about forms!

Forms

What are all the things you have used forms for?

Why do we need forms? Forms allow for two primary things:

  • Users to enter data into our website
  • Process the user input into something meaningful/valuable
What HTML tag is used to create a form on a web page?

The <form> tag

Creating Forms in Flask

Form handling is made easy through the Flask-WTF package, which integrates Flask and WTForms.

from flask import request

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        return process_form()
    else:
        return render_template(...)

Your First Form

In a python file:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        return f'Hello, {name}!'
    return render_template('form.html')

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

In an .html file inside the directory templates, include:

<!doctype html>
<html>
  <body>
    <form method="post">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Form Validation

Imagine you are a content creator with a website that allows users to signup for your newsletter. One of your users readily signs up, but they entered "@hmail.com" instead of "@gmail.com". This is one of the many ways that unintentional input of badly-formatted data can contribute to difficulty for the individual collecting the data. How can we prevent this from happening?

Using validation - the process of checking that data meets certain rules or requirements before it is accepted or processed by your application. This can include:

  • required fields filled in
  • data in correct format (e.g. emails)
  • values are in appropriate ranges (e.g. age can't be negative)

Where can we tell the website to validate input?

  • Client-side: In the browser, using HTML or JavaScript, for quick feedback.
  • Server-side: On the backend, to ensure data is safe and correct before saving or using it (since client-side checks can be bypassed).

Right now, we'll go through an example of server-side using Flask. Firstly, install the following:

pip3 install Flask-WTF

An example:

Main Python file:

from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField
from wtforms.validators import InputRequired, NumberRange, Length

class WelcomeForm(FlaskForm):
    name = StringField('Name', validators=[InputRequired(), Length(min=4, max=30)])
    location = StringField('Location', validators=[InputRequired(),
    Length(min=3, max=50)])
    age = IntegerField('Age', validators=[InputRequired(), NumberRange(min=1, max=140,
    message='Must be between 1 and 140')])
    submit = SubmitField('Submit')

Respective .html file in /templates:

{% extends "base.html" %}
{% block content %}
<h1>Welcome to the website!</h1>
<form action="/" method="post">
{{ form.csrf_token }}
{{ form.name.label }}: {{ form.name(size=40) }} <br>
{{ form.location.label }} {{ form.location(size=60) }} <br>
{{ form.age.label }} {{ form.age() }} <br>
{{ form.submit() }}
</form>
{% endblock %}

Recap

Why do we need forms?

Allowing users to enter data and processing the input into something meaningful.

How do CSRFs happen and how can we prevent these?

Cross-Site Request Forgery attacks occur when a malicious website tricks a user's browser into submitting a request to another site where the user is already authenticated. The target site can't tell that the request wasn't made intentionally by the user because the browser automatically includes session cookies with each request.

By using a CSRF token — a unique, random value generated for each session and included in every form - the server checks that the token matches what it expects. If the token is missing or incorrect, the request is rejected.In Flask, this is commonly handled using the Flask-WTF extension, which automatically adds and checks CSRF tokens.

What's an example of a problem associated with invalid data input and how can validators help?

A user might enter an age as "-5" or leave a required field blank, which can lead to errors in intended functionality or even security issues. Validators in Flask (using Flask-WTF and WTForms) help by automatically checking that form fields meet certain requirements before processing.