Deerled
Deerled

Reputation: 45

how to create a dynamic url from form using flask

I have a form on my home page that is generated from a list of folders on disk. I can't figure out how to route to the next page and add a dynamic url. So that the url reads http://127.0.0.1:5000/projects/ (http://127.0.0.1:5000/projects/banana) (http://127.0.0.1:5000/projects/apple)

@app.route("/")
def home():
    return render_template("home.html", list_projects=list_projects)


@app.route('/', methods=['POST', 'GET'])
def project_select_form():
    project_select = request.form['project']
    return redirect(url_for("project_page"), project=project_select)


@app.route('/projects/<project>', methods=['POST', 'GET'])
def project_page(project):
    return render_template("project_selected.html", project=project)



if __name__ == "__main__":


html

<form method = "POST">
  <select id="project" name="project">
      {% for x in list_projects %}
      <option value="{{ x }}">{{ x }}</option>
      {% endfor %}

  </select>
    <input name="text" type="submit">

</form>

Upvotes: 0

Views: 2219

Answers (2)

Deerled
Deerled

Reputation: 45

The answer was to add an if statement to the form. Otherwise it errors out

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

    if request.form:
        project_select = request.form['project']
        return redirect(url_for("project_page", project=project_select))
    else:
        return render_template("home.html", list_projects=list_projects)

Upvotes: 0

Harshal Parekh
Harshal Parekh

Reputation: 6017

All you need to do is, add a JavaScript/jQuery function that will call the URL.

<form method="GET">
    <select id="project" name="project">
        <option value="a1">a1</option>
        <option value="b1">b1</option>
    </select>
    <input type="button" value="Submit" onclick="myFunction()">
</form>

With this slight modification in your form, you can now have a function like this:

<script>
    function myFunction() {
        var e = document.getElementById("project");
        var list_project = e.options[e.selectedIndex].value;
        var theUrl = "http://127.0.0.1:5000/project/".concat(list_project);
        window.location.replace(theUrl);
    }
</script>

This simply calls the URL, which in turn renders the project_selected.html.

Hope this helps. Good luck.

Upvotes: 2

Related Questions