Part 2 of Build a CRUD Web App with Flask Python Framework

flask python framework logo
Standard

Haven’t yet read the 1st part of the tutorial? Visit: http://tutorialsfordevs.com/tutorials/build-a-crud-web-app-with-flask-python-framework/

Looking for a remote / home based job? Visit http://digitalnomadgigs.com/


In the first part of the tutorial, we defined a Note model:

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    def __init__(self, title, body):
        self.title = title
        self.body = body

Jaapz told me that we don’t have to use a custom __init__ method when creating SQLAlchemy models: https://www.reddit.com/r/flask/comments/4bgisp/how_to_build_a_crud_application_using_flask/d18ygml

So let’s remove our custom __init__ method. Your note model should now only look like this:

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)

We’ll now add a create a note page.

In main.py:

Above:

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

Add this code:

@app.route(“/notes/create”, methods=[“GET”, “POST”])

This route will handle both GET and POST HTTP methods.

If you’re not familiar with HTTP methods, you can refer here: http://www.tutorialspoint.com/http/http_methods.htm

Next, add this code below the route that we added above.

In main.py:

def create_note():
    if request.method == “GET”:
        return render_template(“create_note.html”)
    else:
        title = request.form[“title”]
        body = request.form[“body”]
        note = Note(title=title, body=body)
        db.session.add(note)
        db.session.commit()
        return redirect(“/notes/create”)

If the request method is GET, our function above will render the create_note.html template. If the request method is not equal to GET (In our case, if the request method is not equal to GET, we are assuming that the request method is equal to POST. We are sure that the request method is equal to POST if its not equal to GET because our route only allows GET and POST)

Check the route that we added above and you’ll see this:

methods=["GET", "POST"]

)

Now back to what I was saying, if the request method is not equal to GET, we are retrieving the submitted title and body by the user using request.form[] and passing its values to the title variable and body variable. Next, we are instantiating a Note model and passing the title and body variables into it. The Note instance is passed to the note variable.

Gain the skills you need to be a pro at Python development: http://treehouse.7eer.net/c/245500/245646/3944

Next, we are passing the note variable to db.session.add().

And then we are calling db.session.commit() to save the note to the database. Then we are redirecting the user to the same page.

If you want to understand how SQLAlchemy’s session works, read this article: http://pythoncentral.io/understanding-python-sqlalchemy-session/

In templates folder, create a file and name it create_note.html then put this code inside it:

<form action=”/notes/create” method=”POST”>
    <label>Title</label>
    <input type=”text” name=”title”>
    <label>Body</label>
    <input type=”text” name=”body”>
    <input type=”submit” value=”Create”>
</form>

What we did here is just add an HTML form that has 2 labels, 2 text boxes and a submit button. The 2 text boxes will allow the user to input a title and a description for the post. We also set the method attribute of the form to POST. If we don’t specify a method, it will use GET since it’s the default.

If you’re not familiar with HTML forms, you can refer here: http://www.w3schools.com/html/html_forms.asp

Now try visiting http://localhost:5000/notes/create in your browser. You should see this:

create note page

If you see an error like “Page not found” or “This site can’t be reached”. It’s probably because your server is not running. So make sure to check if the server is running. If it’s not running, run the server using this command while you’re in inside the note_app folder:

python main.py

Looking for a remote / home based job? Visit http://digitalnomadgigs.com/

While you’re in the create note page, enter a title and a body and then click the create a button. You should be redirected to the same page but now the inputs should now be gone.

Now let’s check if the note has been saved in the database. In this tutorial, we will use a tool named SQLite manager: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ . It is a Firefox browser add-on that we can use to manage SQLite databases. Install it and then open your Firefox browser, click tools and then click SQLite manager:

SQLite manager

Find the folder icon in the SQLite manager and click it. Open the SQLite database of your application by opening app.sqlite which is found under the note_app folder.

Now click Tables, click note and click Browse & Search. You should now be able to see the note that we created earlier.

saved note screenshot

What’s next?

In the next part of the tutorial, we will create a note list page which basically lists all the notes that are added in the database. And maybe also add an edit note feature too! 🙂

Feel free to leave a feedback about the tutorial by leaving a comment. I would really appreciate it if you will recommend and also tweet this tutorial 🙂

Share this tutorial w/ your followers on Twitter. Click this link to tweet this tutorial: https://goo.gl/Pl2IuB

The source code of this tutorial is on Github: https://github.com/basco-johnkevin/note-taking-app/tree/master/part2

Want to get updated when I publish part 3 of the tutorial? Subscribe: http://eepurl.com/bVGMwr

Gain the skills you need to be a pro at Python development. Start learning for FREE: http://treehouse.7eer.net/c/245500/245646/3944

Are you looking for a remote/home based job? Visit http://digitalnomadgigs.com/

You can follow me on Twitter: https://twitter.com/johnkevinmbasco

Looking for a developer? I’m accepting web/mobile development projects. Shoot me an email: [email protected]