Flask - Pass argument to URL - 405 Error

552 views Asked by At

I am learning Flask and I am having some trouble passing arguments to a URL for use on another page. For example, I have a form on /index and I would like it to redirect to a /results page where I could print the form data. My attempt is this:

from flask import render_template
from flask import redirect
from flask import url_for

from app import app
from .forms import LoginForm

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        name = form.artistName.data
        return redirect(url_for('result', name=name))
    else:
        return redirect('/index')
    return render_template('index.html',
                           title='Sign In',
                           form=form)

@app.route('/result/<name>')
def result(name):
    return render_template('results.html')

I receive a 405 error Method not allowed for the requested URL when redirecting to the /results page. I would like to construct a URL on /results using the result of the form as an argument.

How can I do this? Many thanks

1

There are 1 answers

2
bingtel On

you defined

@app.route('/result/<name>')

which means its default http method is GET; when this runs:

if form.validate_on_submit():
    # POST method
    name = form.artistName.data
    # redirect Will use 'POST'
    return redirect(url_for('result', name=name))

so , you got Method not allowed for the requested URL.

i think you can add a POST method to @app.route('/result/<name>')