user3788339
user3788339

Reputation: 31

Python Flask get item from HTML select form

Im having trouble getting anything from the shown HTML form

I always get "ValueError: View function did not return a response"

Can somebody help me out here please? I have tried every variation of request.get that I can find on the web. Also if I specify my form should use post it uses get anyway - anybody know why this is?

Im new to flask so forgive my ignorance!

Thanks in advance.

The python file (routes.py)

from flask import Flask, render_template, request
import os
app = Flask(__name__)     
musicpath = os.listdir(r"C:\Users\Oscar\Music\iTunes\iTunes Media\Music")
lsize = str(len(musicpath))
looper = len(musicpath)


@app.route('/')
def home():
    return render_template('home.html', lsize=20, looper=looper, musicpath=musicpath)

@app.route('/pop', methods=['POST', 'GET'])
def pop():
    if request.method == "GET":
      text = request.args.get('som')
      return text
      #Have tried every variation of request.get

@app.route('/about')
def about():
    name = "Hello!"
    return render_template('about.html', name=name)



if __name__ == '__main__':
    app.run(debug=True)

The html file (home.html)

{% extends "layout.html" %}
{% block content %}
  <div class="jumbo">
    <h2>A Music app!<h2>
  </div>
  <div>
        {% if lsize %}
            <form action="/pop">
                <select id="som" size="20">
                {% for i in range(looper):%}
                    <option value="{{i}}">{{ musicpath[i] }}</option>
                {% endfor %}
                </select>
            </form>
        {% endif %}
    </div>
    <a href="{{ url_for('pop') }}">Select,</a>

{% endblock %}

Upvotes: 0

Views: 7114

Answers (3)

Wombatz
Wombatz

Reputation: 5449

The Problem is that your HTML form does not have a name. request.args.get("som") needs an HTML form input with the name "som"

<select name="som" id="som" size="20">

Just change that line and add a name. The form is not interested in the id attribute.

Upvotes: 3

Samuele
Samuele

Reputation: 1

You don't specified the method of the form, you have to do it! For example use this<form method="POST action"/pop">

Upvotes: 0

Menno H&#246;lscher
Menno H&#246;lscher

Reputation: 585

Your form action is /pop. That means that if you submit the form it will do a POST request to the address /pop. Your code does only return a value for a GET request, therefore Flask complains you do not return anything. Write some code to process a POST request and return a text or rendered template.

BTW, in the code for GET you refer to request.args.get('som'); this gives you request arguments (i.e. in the URL), not from the form. som is in the form, so you cannot refer to it this way.

Upvotes: 0

Related Questions