Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 7, 2023 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/266d5e435508ff9336882c9fc7064b30 to your computer and use it in GitHub Desktop.
Save code-boxx/266d5e435508ff9336882c9fc7064b30 to your computer and use it in GitHub Desktop.
Python Flask Dependent Dropdown

PYTHON FLASK DEPENDENT DROPDOWN

https://code-boxx.com/python-flask-dependent-dropdown/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create 2 folders - static, templates
    • Move S3B_selector.js and S3C_selector.css into static.
    • Move S3A_selector.html into templates.
    • Create a virtual environment - virtualenv venv
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask pip install flask
    • Create the database python S1B_create.py
    • Start the server python S1_server.py
  2. Access http://localhost in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) CATEGORY TABLE
CREATE TABLE `category` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`parent` INTEGER DEFAULT 0 NOT NULL,
`name` TEXT NOT NULL
);
CREATE INDEX `idx_parent` ON `category` (`parent`);
-- (B) DUMMY CATEGORIES
INSERT INTO `category` (`id`, `parent`, `name`) VALUES
(1, 0, 'Electronics'),
(2, 0, 'Sports'),
(3, 1, 'Mobile'),
(4, 1, 'Tablet'),
(5, 1, 'Laptop'),
(6, 1, 'Desktop'),
(7, 2, 'Jogging'),
(8, 2, 'Swimming'),
(9, 2, 'Cycling');
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "cat.db"
SQLFILE = "S1A_cat.sql"
# (C) DELETE OLD DATABASE IF EXIST
if os.path.exists(DBFILE):
os.remove(DBFILE)
# (D) IMPORT SQL
conn = sqlite3.connect(DBFILE)
with open(SQLFILE) as f:
conn.executescript(f.read())
conn.commit()
conn.close()
print("Database created!")
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, request, render_template
import sqlite3, json
# (A2) FLASK SETTINGS + INIT
DBFILE = "cat.db"
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
# (B) ROUTES
# (B1) SERVE DEMO PAGE
@app.route("/")
def demo():
return render_template("S3A_selector.html")
# (B2) GET CATEGORIES FROM DATABASE
@app.route("/getcat", methods=["POST"])
def getcat():
data = dict(request.form)
conn = sqlite3.connect(DBFILE)
cat = conn.cursor().execute("SELECT `id`, `name` FROM `category` WHERE `parent`=?", (data["id"],)).fetchall()
conn.close()
return json.dumps(cat)
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
<!DOCTYPE html>
<html>
<head>
<title>Dependent Dropdown Selector</title>
<meta charset="utf-8">
<script src="static/S3B_selector.js"></script>
<link rel="stylesheet" href="static/S3C_selector.css">
</head>
<body>
<form onsubmit="return false;">
<label>Main Category</label>
<select id="cat1" onchange="loadcat(2)"></select>
<label>Sub Category</label>
<select id="cat2"></select>
</form>
</body>
</html>
// (A) LOAD CATEGORY SELECTOR
// level 1 = main category
// level 2 = sub category
function loadcat (level) {
// (A1) GET SELECTED PARENT ID
var data = new FormData();
data.append("id", (level==1 ? 0 : document.getElementById("cat1").value));
// (A2) AJAX FETCH CATEGORIES
fetch("/getcat", { method: "POST", body: data })
.then(res => res.json())
.then(cat => {
// (A2-1) UPDATE HTML SELECTOR
let selector = document.getElementById("cat" + level);
selector.innerHTML = "";
for (let c of cat) {
let opt = document.createElement("option");
opt.value = c[0];
opt.innerHTML = c[1];
selector.appendChild(opt);
}
// (A2-2) CASCADE LOAD SUB-CATEGORY
if (level==1) { loadcat(2); }
});
}
// (B) INIT LOAD
window.onload = () => loadcat(1);
/* (X) DOES NOT MATTER */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
form {
max-width: 400px;
padding: 30px 20px;
border: 1px solid #e1e1e1;
background: #f2f2f2;
}
label, select {
display: block;
width: 100%;
}
label {
margin: 10px 0;
color: #4a4a4a;
}
form label:first-child { margin-top: 0; }
select {
padding: 10px;
border: 1px solid #d5d5d5;
}
md templates
md static
move S3A_selector.html templates
move S3B_selector.js static
move S3C_selector.css static
virtualenv venv
call venv\Scripts\activate
pip install flask
python S1B_create.py
python S2_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S3A_selector.html ./templates
mv ./S3B_selector.js ./static
mv ./S3C_selector.css ./static
virtualenv venv
source "venv/bin/activate"
pip install flask
python S1B_create.py
python S2_server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment