Making the Form Work

Now we have a way to submit a talk, but the web application has no way of displaying the submitted talk. We can build another route + template combo to implement this feature.

New Route - talk

Let’s start with the route. Here is what your app.py should look like, with the new route highlighted:

# app.py

from flask import Flask, render_template, redirect, url_for, jsonify, request
from talk_mashup_bot import talk_mashup_bot

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello world!"

@app.route('/talk/new')
def new_talk():
    title = talk_mashup_bot.generateTitle()
    return render_template('new_talk.html', title=title)

@app.route('/talk', methods=['POST', 'GET'])
def talk():
    if request.method == 'GET':
        return redirect(url_for('new_talk'))

    talk_title = request.form['form-title']
    talk_description = request.form['form-description']

    return render_template('talk.html', title=talk_title, description=talk_description)


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

This is a bit more complicated than the previous route, so let’s look at what’s happening. The first new thing you’ll see is the methods=['POST', 'GET'] inside the route declaration. Here’s we’re telling the application that we’ll accept “POST” requests (essentially to accept our form input) in addition to “GET” requests (the default type of request accepted by a route, typically the type of request a web browser would make when you click a link).

The next part with the following two lines just says if a browser makes a normal request to this route, just display the “new_talk” route (the new talk form) instead.

if request.method == 'GET':
        return redirect(url_for('new_talk'))

The rest of the code in this function is what will happen if the web application receives a “POST” request (in other words, if the form is submitted). Flask gives us a way to pull information from a submitted form using the request.form['form_field_name_here'] syntax, so we pull the title and description from the form and store them in variables called “form-title” and “form-description”.

Finally, we render a new template called “talk.html” in the same way as before, and we pass the title and new description to it so that we can display this data.

New Template - talk.html

We will now make a new template to go along with our new route, where we’ll display the information we collected in the form. Here’s a suggestion for what this should look like:

<h1>Your submitted talk:</h1>

<h2>{{ title }}</h2>
<p>{{ description }}</p>

Create a new file in your templates/ folder of your application called “talk.html” and copy/paste the above into it. Feel free to modify it using your newfound HTML skills! Make sure to save it, then try going to your talk submission page and submitting a new talk:

http://localhost:5000/talk/new