Data management in web applications is a fundamental component of creating interactive and functional experiences. In this article, we will explore how to implement CRUD (Create, Read, Update, Delete) operations in a Flask application using SQLAlchemy, focusing specifically on creating and displaying notes. Mastering these techniques will allow you to develop robust web applications with data persistence, an essential skill for any modern web developer.
How to implement note functionality in our application?
Now that our "note" table has a defined structure and allows the creation of new records, it is time to use our model to interact with the database. The note model includes several methods that allow us to create, update and list all stored notes.
To start, we need to modify our home view to display the notes from the database instead of using static data. Previously we had a challenge ahead of us: converting the notes from simple strings to objects with properties.
@app.route('/')def home(): notes = ["Note 1", "Note 2", "Note 3"] role = "admin" return render_template('index.html', notes=notes, role=role)
#@app.route('/')def home(): notes = [ {"title": "test title", "content": "test content"} ] return render_template('index.html', notes=notes)
We also need to update our HTML file to support the new object structure:
{% for note in notes %} <li> {{ note.title }} <br> {{ note.content }} </li>{% else %} <p>Nonotes have been created yet.</p>{% endfor %}
<a href="{{ url_for('create_note') }}">Adda new note</a>.
The implementation of the else
block inside the for
loop is a powerful feature of Jinja2 that allows us to display an alternative message when the list is empty, thus improving the user experience.
How to create the form to add new notes?
To allow users to create new notes, we need a proper form. Let's modify our existing form to include fields for both title and content:
<form method="POST"> <label for="title">Title</label> <input type="text" name="title" id="title" ><br> <label for="content">Content</label> <input type="text" name="content" id="content"> <br> <button type="submit">Createnote</button></form>.
This form will submit the data via POST method to our note creation path.
How to save the notes in the database?
The most important part is the logic for saving the notes to the database. We need to modify our create_note
function to capture the form data and store it:
@app.route('/create', methods=['GET', 'POST'])def create_note(): if request.method == 'POST': title = request.form.get('title', '') content = request.form.get('content', '')
note_db = Note(title=title, content=content) db.session.add(note_db) db.session.commit()
return redirect(url_for('home'))
return render_template('create.html')
This code performs several key operations:
- Gets the form data (title and content).
- Creates a new instance of the Note template with that data
- Adds the note to the database session
- Commits the transaction with
commit()
- Redirects the user to the main page
It is important to highlight the use of db.session.commit()
, which commits the changes to the database. We could perform multiple operations (add multiple notes) before committing, which would optimize performance in batch operations.
How to display the notes from the database?
To display the notes stored in the database, we need to modify our home
function to query the database:
@app.route('/')def home(): notes = Note.query.all() return render_template('index.html', notes=notes)
With this modification, we are now getting all the notes directly from the database and passing them to our template. SQLAlchemy takes care of converting the database records into Python objects, which makes it much easier to work with them in our templates.
How to improve the functionality of our application?
An important improvement would be to add the ID of each note in the list so that we can easily identify them. This will be especially useful when we implement the editing functionality:
{% for note in notes %} <li> ID: {{ note.id }} - {{ note.title }} <br> {{ note.content }} </li>{% else %} <p>Nonotes have been created yet.</p>{% endfor %}
Displaying the ID is the first step in implementing more advanced operations such as editing and deleting notes, as we will need to uniquely identify each note to perform these actions.
Implementing CRUD operations in web applications with Flask and SQLAlchemy is a structured process that allows you to create robust applications with data persistence. By following these steps, you have learned how to create and display notes in a web application, laying the groundwork for more advanced features such as editing and deleting. What other features would you like to implement in your notes application? Share your ideas in the comments and continue to expand your knowledge of web development.
Want to see more contributions, questions and answers from the community?