Build Website with Flask – Part 4

Rate this post

This is part of our Flask series:

Story: Assume you work in the IT Department of Right-On Realtors. Your boss asks you to create a simple website the Realtors can query to view current Home Sales.

He would like this website created using the Flask plugin.

What is Flask?

Flask is a web app framework created with ease of use in mind. Without much training, you can easily create a simple web application. Flask works with Bootstrap, HTML, CSS, and Jinja (to name a few) to create a website.


Preparation

This article assumes you have completed the following from Part 1, Part 2, and Part 3:

  • Created and Activated a Virtual Environment.
  • Installed all of the required plugins.
  • Created the appropriate folder structure.
  • Created and saved an app.py file to the realtors folder.
  • Added Routes to the app.py file.
  • Added Jinja to the base template.
  • Created and saved HTML files to the realtors/templates folder.
  • Linked to Bootstrap.
  • Added a Bootstrap Navbar to the base template file (base.html).
  • Added Jinja to the HTML pages.
  • Viewed the website in a Browser.

In Part 4, you will learn how to:

  • Add a Form with elements to an HTML page.
  • Add Jinja to the Reports page.
  • Add code to app.py to get the HTML Form working.

Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
from flask import Flask, render_template, request

Add Report Code to Index Page

On the Home page (index.html), we will add a small instructional paragraph for the Realtors and an HTML Form with an input box (<input>) where they can enter a Zip Code from the Sacramento area and submit. On the reports.html page, the submitted Zip Code will display.

{% extends 'base.html' %}

{% block content %}     
    <div class="container">
       <h2>Right-On Home Page</h2>

       <br/><br/>
       Realtors, enter a valid Sacramento Zip Code in the box below
       and press the Search button. Sacramento Home Sales for the
       selected area will display on the Reports page.

       <br/><br/>
       <form action="/reports" method="POST">
            <div class="form-group">20
                <input type="text" maxlength="5" class="form-control shadow-sm sm-white rounded" id="exampleFormControlInput1" 
                placeholder="Zip", name="zip_code">  
            </div>
            <br/><br/>
            <button type="submit" class="btn btn-secondary">Search</button>            
       </form>
    </div>
{% endblock %}
  • Lines [1-3] contain a small instructional paragraph for the Realtors. Feel free to expand upon or modify this text.
  • Lines [4-11] contain HTML Form tags (<form></form>). When you pass data from one HTML page to another, it must be inside these tags. In this case, we have one (1) input box, and one (1) submit button. The input box is used in this instance to collect the Zip Code. The submit button tells the script to take the Zip Code and POST it (method="POST").

Inside the <input> tag line:

  • The maximum length of the textbox is set to five (5) characters/numbers. This option prevents the user from entering more than the requisite amount.
  • A class tag is assigned. Bootstrap has various ways to customize the look and feel of the <input> tag.
  • An id tag is assigned (see Bootstrap for additional details).
  • A placeholder is assigned. The placeholder text will display inside the input box when it is empty.
  • A name is assigned. In this case, zip_code. This name is needed to retrieve the appropriate information.

Let’s save this file and move on to the next file to be updated.

💡 Note: The HTML <br/> represents a new line. Click here for details. Although some coders use the <br> tag, <br/> is the proper way to identify the new line tag. Both ways will work.


Add Report Code to Reports Page

Navigate to and open reports.html located in the templates folder.

The code highlighted in yellow retrieves and displays the zip_code variable sent from the Home page (index.html) using Jinja.

{% extends 'base.html' %}

{% block content %}     
    <div class="container">
       <h2>Reports</h2>

       <br/><br/>
       {{ zip_code }}<br/>

    </div>
{% endblock %}

Let’s save this file and move on to the following file to be updated.


Add Report Code to App File

The code highlighted in yellow connects the Home page HTML Form to the Reports page.

app = Flask(__name__)

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

@app.route('/reports', methods=["POST"])      # reports
def reports():
    zip_code = request.form.get("zip_code")
    return render_template("reports.html", zip_code=zip_code)

@app.route('/contact')      # contact
def contact():
    return render_template("contact.html")
  • Line [1] adds a new argument: methods=["POST"] to the existing route. This argument lets the code know to expect incoming data. In this case, the zip_code variable.
  • Line [3] inside the existing reports() function, retreives the contents of zip_code variable entered on the HTML Form (located on index.html).
  • Line [4] displays reports.html in the Browser and passes the variable zip_code.

Save this file.


Run the Code

Navigate to an IDE. From the command prompt, run the code (instructions in Part 3)

If successful, you should see the following in your Browser:

Enter a Zip Code in the input box and press the Search button. For this example, we entered 95670.

If successful, you are forwarded to reports.html and should see the following in your Browser:

💡 Note: To view any changes, Flask needs to be re-started. To perform this task, navigate to the command prompt and enter CTRL+C (stop), then flask run (re-start).


Summary

In this article, you learned how to:

  • Add a Form with elements to an HTML page.
  • Add Jinja code to the Reports page.
  • Add code to app.py to get the Form working.

What’s Next

In Part 5 of this series, we will:

  • Read in the Real Estate CSV file to a DataFrame.
  • Query the results based on a Zip Code.
  • Display the results on the Reports page.