Get value from Select in Flask

341 Views Asked by At

I am new to flask (and StackOverflow) and I apologise in advance for any mistakes I have made.

I am trying to get selected value from a select tag in flask. I have tried all the solutions of similar questions on stack-overflow, but none of them seem to be working for me. I am confused as to, do I need a button to submit my selected value or does it automatically gets sent when an option is selected.

What I want to do is get value from select tag in html and on the basis of that display some text in a readonly text-area. Flask is not showing any error but at the same time I cannot see the value as well. Thanks a lot!

Python Code

@app.route('/learn', methods=['GET','POST'])
def clearn():
    if request.method == 'POST':
        cat = request.form['category']
        print(cat)
    return render_template('index.html', clearn = cat)

HTML

<form action="/learn" method="POST" class="select_cat" id="select_cat">
    <div class="image fit">
        <div class="12u$">
            <div class="select-wrapper">
                <select name="category" id="category" form="select_cat">
                    <option value="0">- Select Procedure -</option>
                    <option value="opt1">Option 1</option>
                    <option value="opt2">Option 2</option>
                    <option value="opt3">Option 3</option>
                    <option value="opt4">Option 4</option>
                </select>
            </div>
        </div>
        <div class="12u$">
            <textarea class="clearn" name="message" id="message" placeholder="Procedure" rows="6" readonly>{{clearn}}</textarea>
        </div>
    </div>
</form>
1

There are 1 best solutions below

3
jmvcollaborator On BEST ANSWER
PY file

@app.route('/learn', methods=['GET','POST'])
@app.route('/learn/<category>/') //in here you can define the datatype if needed ie. @app.route('/learn/<int:category>/') 

def clearn(category):
    if request.method == 'POST':
    return render_template("index.html", category= category)

HTML file

<div class="12u$">
    <div class="select-wrapper">
        {{category}}
    </div>
</div>