简体   繁体   中英

Is it possible to overwrite the value of <Input type = "hidden"> by letting user select from a drop down list?

I want to assign "0" to my one hot encoded variable in HTML and when if the user select an option, the value will change from "0" to "1"

My drop down list: "apples", "Orange", "grapes"

I want to assign all of them a value of 0 to start then when user select "apple" the value of it changes to "1" when submitted to the predictor

This is my HTML code

<!DOCTYPE html>
<html >
<head>
  <title>BOOM</title>
  <style>
    body {
        font-family: Verdana;
        font-size: 12px;
    }
  </style> 
</head>

<body>
    
    
    <h1>MPrediction</h1>

<form action="/predict"method="post">
    <input type="hidden" name="circle" value="0">
    <input type="hidden" name="triangle" value="0">
    <input type="hidden" name="square" value="0">
    
    <input type="hidden" name="red" value="0">
    <input type="hidden" name="green" value="0">
    <input type="hidden" name="blue" value="0">

    
        <select>
            <option value="none" selected disabled hidden>
              Select A Shape
          </option>
            <option name='circle' value="1">circle</option>
            <option name='triangle' value="1">triangle</option>
            <option name='square' value="1">square</option>
            
        </select>

        <select>
            <option value="none" selected disabled hidden>
              Select A Colour
          </option>
            <option name='red' value="1">red</option>
            <option name='green' value="1">green</option>
            <option name='blue' value="1">blue</option>

        </select>

<button type="submit">Predict</button>
    </form>
   <p>{{ my_prediction }}</p>
</body>
</html>

The problem I have now is that the users cannot change the hidden type input. I have thought of using 2 forms with the first being the hidden input and the second being the select, this will cause one of the predictors to be "01" which machine learning don't accept. Is there any way in flask that the code will choose the second value of the variable selected and the rest will just be "0". Like I select "circle" and the system takes in "0" from the hidden form and "1" from the select form and when it goes to flask it takes "0" for all variables and "1" for the "circle" variable? Please help! I might lose my grade if I can't get this to work.

This is my python Flask code (I am using jupyter notebook)

import numpy as np
from flask import Flask, request, render_template
import joblib

app = Flask(__name__)
model = joblib.load('MC_Model.pkl')

@app.route('/')
def home():
    return render_template('BOM.html')


@app.route('/predict',methods=['POST'])
def predict():

    form_data = [float(x) for x in request.form.values()]
    features = [np.array(form_data)]
    prediction = model.predict(features)

    return render_template('BOM.html', MC_prediction='Usage Amount:{} '.format(prediction[0]))

if __name__ == "__main__":
    app.run(debug=False)

As for me your selects and options are totally wrong, and you don't need hidden .

You should have name in <select> and every <option> should have uniq value - it can be index in features

    <select name="shape">
        <option value="" selected disabled hidden>Select A Shape</option>
        <option value="0">circle</option>
        <option value="1">triangle</option>
        <option value="2">square</option>
    </select>

and then you don't need hidden and in Flask you can get value and use as index

features = [np.zeros(6)]

shape = request.form.get('shape')

if shape:  # if shape is not None:
    index = int(shape)
    features[0][index] = 1

I add also code which assigns "selected" to option from previous selection.

<option value="0" {% if shape == 0 %}selected{% endif %}>circle</option>

It needs to send shape , color to template.


Full working example.

I use render_template_string to have HTML in code so other people can simply copy and run it.

from flask import Flask, request, render_template_string
import numpy as np

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def home():
    # default values for `GET`
    color = None
    shape = None
    features = [np.zeros(6)]
    text = 'Usage Amount: ???'
    
    if request.method == 'POST':
        color = request.form.get('color')
        print('color:', color)
        
        shape = request.form.get('shape')
        print('shape:', shape)
                  
        if color:
            index = int(color)
            features[0][index] = 1
        if shape:
            index = int(shape)
            features[0][index] = 1
        print(features)
        
        #prediction = model.predict(features)
        prediction = [np.random.randint(0, 100)]
        
        text = 'Usage Amount: {}'.format(prediction[0])
                
    return render_template_string('''
<form action="/" method="POST">
    <select name="shape">
        <option value="" {% if not shape %}selected{% endif %} disabled hidden>Select A Shape</option>
        <option value="0" {% if shape == 0 %}selected{% endif %}>circle</option>
        <option value="1" {% if shape == 1 %}selected{% endif %}>triangle</option>
        <option value="2" {% if shape == 2 %}selected{% endif %}>square</option>
    </select>

    <select name="color">
        <option value="" {% if not color %}selected{% endif %} disabled hidden>Select A Colour</option>
        <option value="3" {% if color == 3 %}selected{% endif %}>red</option>
        <option value="4" {% if color == 4 %}selected{% endif %}>green</option>
        <option value="5" {% if color == 5 %}selected{% endif %}>blue</option>
    </select>

    <button type="submit">Predict</button>
</form>

<p>features: {{ features }}</p>
<p>prediction: {{ prediction }}</p>
''', prediction=text, features=features[0], color=color, shape=shape)

if __name__ == "__main__":
    app.run(debug=False)

I was thinking to use list with shapes and colors to generate options with for -loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM