Tony Tony - 1 month ago 6
Python Question

Redirect with data parameter in flask

I was trying to learn flask and came across the following problem.This is the example that i was trying to implement.

@app.route('/poll', methods = ['GET', 'POST'])
def poll():
form = PollForm()

if form.validate_on_submit():
return render_template('details.html', form = form)

return render_template('poll.html', form=form)


But i wanted to have a different url mapping for details.html, for that purpose i created another route as,

@app.route('/details/<form>')
def details():
return render_template('details.html', form = form):


For using this i have used

return redirect(url_for('details', form=form))


in poll method inside the if condition. And when i tried to access the same from detail.html , i am not able to get it as a object. When tried to replace form with a string, it worked fine. Could you please suggest some mechanism to access form as an object inside the /details route ?

Edit

I was asking something like this is possible.

@app.route('/poll', methods = ['GET', 'POST'])
def poll():
form = PollForm()

if form.validate_on_submit():
@app.route('/details')
return render_template('details.html', form = form)

return render_template('poll.html', form=form)


whenever we get inside the if condition the url will be /poll/details.Or is there any
way to make this kind of url nesting, starting from a root url then child urls gets added depending on the business logic.

Answer

You cannot just put a form object into a URL, no. A redirect() is a response, telling the browser to go load a different URL, the form object is not something you can easily cram into a URL path element.

If you don't need to see a different URL in the browser location bar, don't use a redirect but simply call a different function:

def details(form): 
   return render_template('details.html', form = form):

@app.route('/poll', methods = ['GET', 'POST'])
def poll():
    form = PollForm()

    if form.validate_on_submit():
        return details(form)

    return render_template('poll.html', form=form)

If you do need a different URL in the browser, then have the <form> element post to the /details route, not the /poll route.