在不使用ajax的情况下根据Flask python中的先前选择填充下拉菜单? [英] Populate the drop-down menu based on previous selection in Flask python without using ajax?
问题描述
我有一个数据框形式的csv文件,该文件由位置,设备和单位组成。位置可能是使用不同单元和设备的重复位置。
我要使用4个下拉菜单
- 位置
- 单位
- 子单位
- 设备
和一个提交按钮,显示所有选定的字段。
在选择位置时,应显示所有基于位置的唯一位置(例如PA),选择的单位将显示为
单位
>:LAN
>:WAN
子单元
>。 LAN交换机
>。 WAN交换机
设备
> D2
> D4
这是问题陈述的一个示例。原始文件包含数千个位置和相关单位。
>定位设备单元
>美国D1 LAN核心
> PA D2 LAN交换机
> BLR D3 LAN核心
> PA D4 WAN交换机
> MEL D5 DC地铁
app.py:
<从烧瓶导入烧瓶中的pre>
,render_template,请求
导入熊猫为pd
app = Flask(__ name__)
app.debug = True
@ app.route('/',方法= ['GET'])
def dropdown():
total_data = pd.read_csv( CPS.csv)
print(total_data)
data = total_data ['LOCATION']。unique()
print(data)
return render_template('index.html',data = data)
如果__name__ == __main__:
app.run()
index.html
<!DOCTYPE html>
< html lang = zh-CN>
< head>
< meta charset = UTF-8>
< title> Dropdown< / title>
< / head>
< body>
<选择名称=数据方法= GET action = />
{%for data in row%}
< option value = {{row}} SELECTED> {{row}}< / option>
{%endfor%}
< / select>
< / body>
< / html>
如果要避免进行ajax请求,则应考虑使用诸如 IndexedDB 。
您希望将信息保留在服务器端并动态访问,可以通过以下方式实现该目的:
from flask_wtf import从wtforms导入的FlaskForm
从flask导入的SelectField
从烧瓶导入的Flask,render_template,request,json将
导入为pd
类LocationsForm(FlaskForm):
位置= SelectField('Locations')
@ app.route('/',methods = ['GET','POST'])
def dropdown():
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>')
def device_choice(value):
location_choosen =值
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>')
def unit_choice(value):
#您可以实现通过遵循与设备相同的模型
我创建了一个表格,该表格使用值动态填充仅限位置。然后呈现该表单。
在我的JS脚本中,我放置了一个事件,只要位置字段发生变化,该事件就会触发。
每次更改时,我都会将所选值(位置
)发送到 device_choice路由
并找到与此位置关联的所有设备。我将设备作为列表返回并填写适当的选择字段(设备
)
HTML的SIDE
<!DOCTYPE html>
< html lang = zh-CN>
< head>
< meta charset = UTF-8>
< title> Dropdown< / title>
< / head>
< body>
{{form.hidden_tag()}}
{{form.locations(class _ = form-control)}}
< select class = form-control devices id = 设备< / select>
< select class = 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(允许选择数据。设备){
optionHTML + ='< option value ='+ opt +'>'+ opt +'< / option>';
}
devices.innerHTML = optionHTML;
});
});
}
< / script>
< / html>
您也只需对单元应用相同的逻辑...
I have a csv file in the form of dataframe which consist of location, Device and unit. Locations may be repeated locations with different units and devices.
I want 4 dropdown menu with
- Location
- Unit
- Sub Unit
- Device
And a submit button, which displays all the selected fields.
On selection of location, it should display all unique locations based on the selection of location like PA, select unit will display like
Unit
>:LAN
>:WAN
Subunit
>. LAN Switch
>. WAN switch
Device
> D2
> D4
This is a example of the problem statement. Original file consist thousand locations and related units.
> Location Device Unit
> USA D1 LAN core
> PA D2 LAN Switch
> BLR D3 LAN core
> PA D4 WAN switch
> MEL D5 DC metro
app.py:
from flask import Flask, render_template, request
import pandas as pd
app = Flask(__name__)
app.debug = True
@app.route('/', methods=['GET'])
def dropdown():
total_data = pd.read_csv("CPS.csv")
print(total_data)
data = total_data['LOCATION'].unique()
print(data)
return render_template('index.html', data=data)
if __name__ == "__main__":
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dropdown</title>
</head>
<body>
<select name= data method="GET" action="/">
{% for row in data %}
<option value= "{{row}}" SELECTED>{{row}}</option>"
{% endfor %}
</select>
</body>
</html>
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
class LocationsForm(FlaskForm):
locations = SelectField('Locations')
@app.route('/', methods=['GET', 'POST'])
def dropdown():
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>')
def device_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>')
def unit_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>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dropdown</title>
</head>
<body>
{{ form.hidden_tag() }}
{{ form.locations(class_="form-control") }}
<select class="form-control devices" id="devices"></select>
<select class="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...
这篇关于在不使用ajax的情况下根据Flask python中的先前选择填充下拉菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!