Skip to content

CRUD Exercises

These exercises put everything together. By the end you will have a fully working patient app with a search feature.


Exercise 1 - Add Three Patients

Run your app. Add three patients using the form. Confirm all three appear in the table without refreshing the page.

Then stop Flask, restart it, and open the page again. All three should still be there.


Exercise 2 - Update a Name

Pick one of your patients. Click Edit. Change their name. Click Save Update.

Confirm the new name appears in the table. Then restart Flask and check the name is still updated in the database.


Exercise 3 - Delete and Confirm

Delete one of your patients. Confirm they disappear from the table.

Restart Flask. Confirm they are gone from the database - not just hidden on the page.


Exercise 4 - Add an Email Field

Add a new field to your Patient model:

email = pookiedb.CharField(max_length=200)

Delete your patients.sqlite3 file and let PookieDB recreate it with the new column.

Update: - The form to include an email input - The addPatient() function to include email in the JSON body - The Flask POST route to save data["email"] - The get_patients() route to include "email" in the response - The table to show the email column


Exercise 5 - Search by Name

A query parameter is a ?key=value added to the end of a URL. It is different from a URL parameter - it is not part of the path, just extra information for filtering.

Example: /patients?name=Alice - the path is still /patients, and ?name=Alice is the query parameter.

In Flask, you read it with:

name = request.args.get("name", "")

Add a search endpoint to app.py:

@app.route('/patients/search', methods=['GET'])
def search_patients():
    name = request.args.get("name", "")
    results = Patient.objects.filter(name=name)
    data = [{ "id": str(p.id), "name": p.name, "age": p.age } for p in results]
    return jsonify(data)

Then add a search box to your template:

<input id="search" type="text" class="form-control mb-2" placeholder="Search by name">
<button onclick="searchPatients()" class="btn btn-secondary">Search</button>

And the JavaScript function:

function searchPatients() {
    let name = document.getElementById("search").value
    fetch("/patients/search?name=" + name)
        .then(response => response.json())
        .then(results => {
            let tbody = document.getElementById("patient-rows")
            let html = ""
            for (let patient of results) {
                html += `<tr><td>${patient.name}</td><td>${patient.age}</td></tr>`
            }
            tbody.innerHTML = html
        })
        .catch(error => console.log("Error:", error))
}

Test it: add two patients named "Alice" and one named "Bob". Search for "Alice" - only the two Alices should appear.


← Delete - Removing a Record    Next: Personal Website - Home →