如何在网页上用数据框中的列名和唯一值生成动态选择字段?

2024-04-28 22:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的web应用程序允许用户上传他们的Excel文件,然后在我的flask应用程序中读取并转换成数据帧。随后,我的应用程序将对数据帧进行过滤,以从数据帧中删除不必要的记录。为此,我计划设置两个动态选择字段:

第一个选择字段-包含数据框中的列名列表 第二个选择字段-第一个选择字段中所选值的对应唯一值。你知道吗

那我该怎么做呢??你知道吗

我看了一个视频,教我如何使用烧瓶形式做这些动态领域。但我似乎无法定制他的方式来适应我的https://www.youtube.com/watch?v=I2dJuNwlIH0

烧瓶侧码(应用程序类型)地址:

class Form(Form):
    column = SelectField('column', choices=list(upload_df.columns.values))
    unique_value = SelectField('unique_value', choices=[]) 

@app.route('/upload_file')
def upload_file():
    return render_template('upload.html')

@app.route('/testing_field', methods=['GET', 'POST'])
def testing():
    if request.method == 'POST':
        file = request.files['datafile']
        if file and allowed_file(file.filename):
            global upload_df
            upload_df = pd.read_excel(file)
            col = list(upload_df.columns.values)
            form = Form()
            global col_uni_val_dict
            for i in col:
                col_uni_val_dict[i] = upload_df[i].unique()
            form.unique_value.choices = (col_uni_val_dict[col[0]]).tolist()

    return render_template(
        'index2.html',
        form=form
    )

@app.route('/col/<col>')
def unique_val(col):
    unique_values = col_uni_val_dict[col].tolist()

    return jsonify({'unique_val' : unique_values})

HTML侧码:

<html>
<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>Document</title>
</head>
<body>
    <form method="POST">
        {{ form.crsf_token }}
        {{ form.column }}
        {{ form.unique_value }}
        <input type="submit">
    </form>
    <script>
        let col_select = document.getElementById('column');
        let uv_select = document.getElementById('unique_value');

        col_select.onchange = function(){
            col = col_select.value;

            fetch('/col/' + col).then(function(response){

                response.json().then(function(data){
                    let optionHTML = "";

                    for (let uv of data.unique_val) {
                        optionHTML += '<option value="' + uv + '">' + uv + '</option>';
                    }

                    uv_select.innerHTML = optionHTML;

                });
            });
        }
    </script>
</body>
</html>

期望:网页上有2个动态选择字段 实际:不断得到不同的错误,如-->;类型错误:无法解包不可iterable int对象


Tags: 数据form应用程序dfvaluehtmlcolumncol