1

I am working on a Flask project that has a simple page which gets input from the users and returns back an output. I am trying to see if I can get a dynamic URL for the web page. Given below are my form and route for this web page:

Form

<form action=""enctype="multipart/form-data"
          method="POST">
        {{form.hidden_tag()}}
<table>
{{ render_field(form.name, size=50) }}
    <tr class="submit">
        <td>
            <button type="submit">Report</button>
        </td>
    </tr>
</table>

Views

@app.route('/users', methods=['GET', 'POST'])
def users():
    form = UsersForm()
    if form.validate_on_submit():

        output = user(name=form.name.data)

        return send_file(output, attachment_filename = f'UserReport_{name}.csv', as_attachment=True)

    return render_template('name', form=form)

The above works just fine.

Page URL is www.website.com/name

I however am trying to see if I can have the webpage URL set to change dynamically based on the value entered in the form (name field). For example, if name is person1, I would like to have the URL set to www.website.com/name/person1

scott martin
  • 1,253
  • 1
  • 14
  • 36
  • Python Flask has a redirect function, maybe you can use that? --> https://stackoverflow.com/questions/14343812/redirecting-to-url-in-flask – Kevin Müller Apr 24 '19 at 11:52

1 Answers1

0

Since your route is set to /users, shouldn't it be www.website.com/users/person1 ?

For dynamic URLs, you could try something like the following

@app.route('/users/<username>', methods=['GET', 'POST'])
def users(username):
...

To access say /users/person1, you can then use return redirect as follows :

return redirect(url_for("users",username=form.name.data))

Relevant : How to generate dynamic urls in flask?

YAMAZAKI1996
  • 35
  • 1
  • 10
  • yes I am trying to have the page redirected to `www.website.com/users/person1`. When I tried `@app.route('/users/', methods=['GET', 'POST']) def users(username): ...` I keep getting `GET /users HTTP/1.1" 404 -` – scott martin Apr 24 '19 at 12:07
  • strange, if you passed username correctly, you should be getting /users/something instead. Are you sure that the username variable is being passed correctly to url_for ? – YAMAZAKI1996 Apr 24 '19 at 12:10