Making the Form Work

Now we have a form to submit a book, but when you press the “Submit” button, nothing happens. Let’s make this work.

New Route - /book

Uncomment the following code in your app.py file:

# Create a new book with the data submitted from the web form, and save it in the database
# If a form is not submitted (ie, it is a GET request), redirect user to the new book form
@app.route('/book', methods=['POST', 'GET'])
def submit_book():
    # If the HTTP request method is GET, redirect to the new book form
    if request.method == 'GET':
        return redirect(url_for('new_book'))

    # Gather the book data from the submitted form
    book_title = request.form['form-title']
    book_cover_image_url = request.form['form-cover-image']
    book_description = request.form['form-description']
    book_reason = request.form['form-reason']
    # Record the time the form was submitted using datetime.now() method
    book_timestamp = datetime.datetime.now()

    # Create a new "Book" object using the submitted data
    new_book = Book(title=book_title, cover=book_cover_image_url, description=book_description, reason=book_reason, created_at=book_timestamp)
    # Save the new "Book" object to the database
    new_book.save()

    # Redirect to the details page for the newly submitted book
    return redirect(url_for('show_book', book_id = new_book.id))

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 GET request to this route without any data, just redirect the user to the “new_book” route (the “new book” form that we just created) instead.

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

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, description, etc from the form and store them in variables called “form-title”, “form-description”, etc. For the last piece of data, the book_timestamp, we use a built-in Python library to get a string containing the current date and time.

In the next part, we’re going to create a new “Book” object that contains all the data we just pulled from the form. This “Book” object corresponds to the “Book” model we defined earlier when we were setting up our database. On the next line, you can see we’re saving this new Book object to the database by calling its .save() method.

Finally, we redirect the user to another route called “show_book”, passing it the new book’s ID. This route doesn’t exist yet, but we’ll also create it. As you might guess from its descriptive name, this route will show details about a particular book. The reason we’re creating this as a new route is that we’ll want to use this in multiple places, and we don’t like to repeat ourselves when we’re writing code! You’ll see how we use that route a second time later on.

Show Book Route

Uncomment this code from your app.py:

# Retrieve a given book (by ID) from the database, and show a "full record" page for that book.
@app.route('/book/<book_id>')
def show_book(book_id):
    # Query the database for the book by its ID
    selected_book = Book.get(Book.id == book_id)

    # Render a page using the data from that book
    return render_template('book.html', book=selected_book)

This is a shorter route, but it has some things we haven’t seen before. The first thing to notice is it accepts a user-specified parameter in the URL:

@app.route('/book/<book_id>')

So we can hit this route by going to something like “http://localhost:3000/book/1” or “http://localhost:3000/book/2” for example. We’re passing the ID of a particular book in the place of <book_id>. We tell our show_book() function about this by having it accept an argument with the same name as we gave to the parameter in the URL above, in this case: book_id.

def show_book(book_id):

We then have access to the passed in ID within our function, and we can use it. Within the function, we query the database for the book with the ID that the user has passed in. We use the Book model to query for books, and use the .get() function to get a single book. We tell it that we’d like the book with an id equal to the book_id parameter supplied in the URL.

selected_book = Book.get(Book.id == book_id)

Finally, we render the “book.html” template, and pass it the data that we got from the database. Within the template, this data will be available through the variable “book”.

Try it out!

With this, we should be able to submit new books, and see the data we submitted printed in the browser. Try going to your book submission page and submitting a new book:

http://localhost:3000/book/new