Populate The Drop-down Menu Based On Previous Selection In Flask Python Without Using Ajax?
Solution 1:
If you want to avoid going through an ajax request then you should consider registering your datas on the client side, by using technologies such as IndexedDB.
But if you want to keep your information on the server side, and access it dynamically, here's how you can implement that:
from flask_wtf import FlaskForm
from wtforms import SelectField
from flask import Flask, render_template, request, jsonify
import pandas as pd
classLocationsForm(FlaskForm):
locations = SelectField('Locations')
@app.route('/', methods=['GET', 'POST'])defdropdown():
total_data = pd.read_csv("CPS.csv")
data = total_data['LOCATION'].unique().tolist()
form = LocationsForm()
form.locations.choices = [(i, i) for i in data]
return render_template(form=form)
@app.route('/device_choice/<value>')defdevice_choice(value):
location_choosen = value
df = pd.read_csv("CPS.csv")
df = df.set_index(["LOCATION"])
df1 = df.loc[location_choosen, 'Device'].tolist()
return jsonify({'Devices': df1})
@app.route('/unit_choice/<value>')defunit_choice(value):
# YOU CAN IMPLEMENT THIS BY FOLLOWING THE SAME MODEL AS THE DEVICES
I create a form that I populate dynamically with the values of the locations only. then I render the form.
In my JS script I put an event that is triggered whenever there is a change in the field of locations.
At each change I send the selected value (location
) to the device_choice route
and find all the devices associated with this location. I return the devices as a list and fill in the appropriate selectfield (devices
)
HTML's SIDE
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>Dropdown</title></head><body>
{{ form.hidden_tag() }}
{{ form.locations(class_="form-control") }}
<selectclass="form-control devices"id="devices"></select><selectclass="form-control unit"id="unit"></select></body><script>let location = document.getElementById('locations');
let devices = document.getElementById('devices');
location.onchange = function(){
value = location.value;
fetch('/device_choice/' + value).then(function(response){
response.json().then(function(data){
let optionHTML = '';
for(let opt of data.Devices){
optionHTML += '<option value ="' + opt + '">' + opt + '</option>';
}
devices.innerHTML = optionHTML;
});
});
}
</script></html>
You just have to apply the same logic for the units too...
Post a Comment for "Populate The Drop-down Menu Based On Previous Selection In Flask Python Without Using Ajax?"