LearninBits

Forms and User Input: The Gateway to Interactive Web Apps

Hey there, wonderful people! 🌟

Today, we’re unlocking a new level in our web development journey—making our website interactive through forms. Imagine having a magical mailbox where visitors can drop messages, suggestions, or even orders for your bookstore. That’s what forms can do!

What is a Web Form?

Picture a paper form at a doctor’s office where you fill in your details. A web form is the digital version of that. It allows users to submit data to the web server for processing. Think of it as a magical doorway that takes users’ wishes (input) and turns them into reality (processed data).

HTML Forms: The Basics

HTML forms are like the blueprint of that magical doorway. They define what kind of data the users can submit.

Here’s what a basic HTML form looks like:

<form action="/submit" method="post">

  <label for="name">Name:</label>

  <input type="text" id="name" name="name">

  <input type="submit" value="Submit">

</form>

In this example, we have:

  • `<form>`: This tells the browser we’re starting a form.
  • `action=”/submit”`: This specifies where to send the form data when the user hits “Submit.”
  • `method=”post”`: This tells the browser to use the POST HTTP method to send data.
  • `<input>`: This is where the user types in their name.

Creating a Simple Contact Form

Let’s create a simple form that allows users to submit their name and email. Create a new HTML file in your templates folder and call it contact.html.

Here’s some basic HTML to start:

<form action="/submit" method="post">

  <label for="name">Name:</label>

  <input type="text" id="name" name="name"><br>

  <label for="email">Email:</label>

  <input type="email" id="email" name="email"><br>

  <input type="submit" value="Submit">

</form>

Handling Form Submissions in Flask

Remember that `action=”/submit”` in our HTML form? We need to create a Flask route that handles this submission.

Here’s how:

from flask import request

@app.route("/contact")

def contact():

    return render_template("contact.html")

@app.route('/submit', methods=['POST'])

def submit():

    name = request.form['name']

    email = request.form['email']

    return f"Thank you {name}! We've received your email address: {email}."

Practical Example: A User Feedback Form

For our practical example, let’s create a user feedback form for our bookstore. Users will be able to submit their name, email, and a short message.

Create a new template called `feedback.html` and add a form similar to the one we created earlier. Don’t forget fields for the name, email, and message.

<form action="/feedback" method="post">

    <div>

        <label for="name">Name:</label>

        <input type="text" id="name" name="name"><br>

    </div>

    <div>

        <label for="email">Email:</label>

        <input type="email" id="email" name="email"><br>

    </div>

    <div>

        <label for="message">Message:</label>

        <input type="text" id="message" name="message"><br>

    </div>

    <input type="submit" value="Submit">

</form>

Then, create a new Flask route that handles this feedback:

@app.route('/feedback', methods=['GET', 'POST'])

def feedback():

    if request.method == 'POST':

        name = request.form['name']

        email = request.form['email']

        message = request.form['message']

        return f"Thank you, {name}! We've received your feedback."

    return render_template('feedback.html')

Using Flask-WTF for Forms

While handling forms manually is okay, Flask provides a more magical tool called Flask-WTF. It makes form handling simpler and more secure.

To use it, you’ll need to install it first:

pip install Flask-WTF

Then, you can create forms like this:

from flask_wtf import FlaskForm

from wtforms import StringField, SubmitField

class ContactForm(FlaskForm):

    name = StringField('Name')

    email = StringField('Email')

    submit = SubmitField('Submit')

Using Flask-WTF for Forms: A Practical Example

Flask-WTF is like a Swiss Army knife for handling forms in Flask. It comes with a bunch of features to make your life easier. Let’s use it to create a feedback form for our bookstore.

Step 1: Installing Flask-WTF

First, make sure you have Flask-WTF installed and also install the email validator. You can install them using pip if you haven’t already:

pip install Flask-WTF

pip install email_validator

Step 2: Create the Form Class

Create a new Python file called forms.py in your project folder. Inside this file, define your form as a class:

from flask_wtf import FlaskForm

from wtforms import StringField, TextAreaField, SubmitField

from wtforms.validators import DataRequired, Email

class FeedbackForm(FlaskForm):

    name = StringField('Name', validators=[DataRequired()])

    email = StringField('Email', validators=[DataRequired(), Email()])

    message = TextAreaField('Message', validators=[DataRequired()])

    submit = SubmitField('Submit')

Here, we’re using some validators to ensure that the fields are not empty and that the email is valid.

Step 3: Update the Feedback Route

Now, let’s use this form in our feedback route. Open your `app.py` and import the `FeedbackForm` class:

from forms import FeedbackForm

Then update your /feedback route:





CSRF Protection

If you’re using Flask-WTF’s CSRF protection (which is enabled by default), make sure you’ve configured a secret key for your Flask application:

Step 4: Update the Feedback Template

Last but not least, let’s update the feedback.html template to use the Flask-WTF form:

Here, {{ form.hidden_tag() }} is for CSRF protection, a security feature provided by Flask-WTF. The rest of the form fields are rendered dynamically using the form instance.

Conclusion

Wow, you’ve done it! 🎉 You’ve learned how to create web forms, handle user input in Flask, and even use Flask-WTF to make your life easier. Forms are the gateway to making interactive and dynamic web apps, and now you hold the key!

Next time, we’ll deep-dive into HTTP methods in Flask, where you’ll learn how to perform different types of actions on your web app.

Leave a Reply

Layer 1