0
votes

i followed miguel grinberg tutorial and now i'm applying what i learned in a side project but in all cases i came a cross some problem which i ignored at first and thought it is my mistake but after investigation i can't find why this behavioud happens, the problem is when i try to go to any url within the website while not logged on log-in screen comes but after that the original requested page is not loaded successfully and flask throughs BuildError exception.

below is my code samples

@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
    return redirect(url_for('index'))

form = LoginForm()

if form.validate_on_submit():
    user = User.query.filter_by(username= form.username.data).first()
    if user is None or not user.check_password(form.password.data):
        return redirect(url_for('login'))
    login_user(user)
    next_page = request.args.get('next')
    if not next_page or url_parse(next_page).netloc != '':
        return redirect(url_for('index'))

    return redirect(url_for(next_page))

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

as you can see i'm getting next parameter and doing some security checks if it exists then redirecting to next_page url , but what happens is that there is build error, for exmpale something like the following

BuildError: Could not build url for endpoint u'/user/4556'. Did you mean
'user' instead?

while user view function looks like this

@app.route('/user/<username>', methods=['GET'])
@login_required
def user(username):
    ....   
1

1 Answers

2
votes

Instead of

return redirect(url_for(next_page))

you probably want

return redirect(next_page)

Your "next" parameter would look like "/user/4556" but you don't have an endpoint called "/user/4556", so you don't want to pass that to url_for. Passing the string directly to redirect will suffice.