article

Saturday, April 4, 2020

Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy


Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy

Database Table

CREATE TABLE countries (
id INTEGER PRIMARY KEY,
name STRING (60)

);

INSERT INTO countries (id, name) VALUES (171, 'Philippines');
INSERT INTO countries (id, name) VALUES (227, 'United States of America');

CREATE TABLE state (
id INTEGER PRIMARY KEY,
name STRING (60),
country_id INTEGER

);

INSERT INTO state (id, name, country_id) VALUES (1, 'ARMM', 171);
INSERT INTO state (id, name, country_id) VALUES (2, 'Bicol', 171);
INSERT INTO state (id, name, country_id) VALUES (3, 'Central Luzon', 171);
INSERT INTO state (id, name, country_id) VALUES (4, 'Central Mindanao', 171);
INSERT INTO state (id, name, country_id) VALUES (5, 'Alabama', 227);
INSERT INTO state (id, name, country_id) VALUES (6, 'Alaska', 227);
INSERT INTO state (id, name, country_id) VALUES (7, 'Arizona', 227);
INSERT INTO state (id, name, country_id) VALUES (8, 'California', 227);
INSERT INTO state (id, name, country_id) VALUES (9, 'Florida', 227);

CREATE TABLE city (
id INTEGER PRIMARY KEY,
state STRING (60),
name STRING (60),
stateid INTEGER

);

INSERT INTO city (id, state, name, stateid) VALUES (1, 'CA', 'Anaheim', 8);
INSERT INTO city (id, state, name, stateid) VALUES (2, 'NV', 'Arden-Arcade', 8);
INSERT INTO city (id, state, name, stateid) VALUES (3, 'CA', 'Bakersfield', 8);
INSERT INTO city (id, state, name, stateid) VALUES (4, 'CA', 'Carson', 8);
INSERT INTO city (id, state, name, stateid) VALUES (5, 'NV', 'Daly City', 8);
INSERT INTO city (id, state, name, stateid) VALUES (6, NULL, 'Angeles City', 3);
INSERT INTO city (id, state, name, stateid) VALUES (7, NULL, 'Olongapo', 3);
INSERT INTO city (id, state, name, stateid) VALUES (8, NULL, 'San Fernando', 3);
INSERT INTO city (id, state, name, stateid) VALUES (9, NULL, 'Tarlac', 3);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#app.py
from flask import Flask, render_template, request, jsonify, json
from flask_sqlalchemy import SQLAlchemy 
from wtforms import SelectField
from flask_wtf import FlaskForm
 
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
db = SQLAlchemy(app)
 
class Country(db.Model):
    __tablename__ = 'countries'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
  
class State(db.Model):
    __tablename__ = 'state'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    country_id = db.Column(db.Integer)
  
class City(db.Model):
 __tablename__ = 'city'
 
 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.String(60))
 stateid = db.Column(db.Integer)
 
class Form(FlaskForm):
    country = SelectField('country', choices=[])
    state = SelectField('state', choices=[])
    city = SelectField('city', choices=[])
         
@app.route('/', methods=['GET', 'POST'])
def index():
    form = Form()
    form.country.choices = [(country.id, country.name) for country in Country.query.all()]
  
    if request.method == 'POST':
       city = City.query.filter_by(id=form.city.data).first()
       country = Country.query.filter_by(id=form.country.data).first()
       state = State.query.filter_by(id=form.state.data).first()
       return '<h1>Country : {}, State: {}, City: {}</h1>'.format(country.name, state.name, city.name)
    return render_template('index.html', form=form)
 
@app.route('/state/<get_state>')
def statebycountry(get_state):
    state = State.query.filter_by(country_id=get_state).all()
    stateArray = []
    for city in state:
        stateObj = {}
        stateObj['id'] = city.id
        stateObj['name'] = city.name
        stateArray.append(stateObj)
    return jsonify({'statecountry' : stateArray})
  
@app.route('/city/<get_city>')
def city(get_city):
    state_data = City.query.filter_by(stateid=get_city).all()
    cityArray = []
    for city in state_data:
        cityObj = {}
        cityObj['id'] = city.id
        cityObj['name'] = city.name
        cityArray.append(cityObj)
    return jsonify({'citylist' : cityArray})
  
  
if __name__ == '__main__':
    app.run(debug=True)
</get_city></get_state>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy</title>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask Dynamic Select Box using Flask-WTF, javascript and SQLAlchemy</h2></p>
        <form method="POST">
          {{ form.csrf_token}} 
      <div class="form-group">
    <label for="email">Country:</label>
    {{ form.country(class="form-control") }}
   </div>
   <div class="form-group">
    <label for="email">State:</label>
    {{ form.state(class="form-control")}}
   </div>
   <div class="form-group">
    <label for="email">City:</label>
    {{ form.city(class="form-control")}}
   </div>
    <input type="submit" class="btn btn-success" btn-lg>
  </form>
        </div>
 </div>
</div>
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');
 
country_select.onchange = function(){
 country = country_select.value;
 <!-- alert(country); -->
 fetch('state/' + country).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (state of data.statecountry) {
    optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
   }
   state_select.innerHTML = optionHTML;
  });
 });
}
state_select.onchange = function(){
 city = state_select.value;
 fetch('city/' + city).then(function(response){
  response.json().then(function(data) {
   optionHTML = '';
   for (city_rs of data.citylist) {
    optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
   }
   city_select.innerHTML = optionHTML;
  });
 });
}
</script>
</body>
</html>

Related Post