【问题标题】:Passing data into flask template将数据传递到烧瓶模板
【发布时间】:2016-03-26 10:11:33
【问题描述】:

在登录表单验证期间,我查询用户并将对象存储在表单实例中。我想将用户对象传递到模板中。在Python, Flask - Passing Arguments Into redirect(url_for()) 之后,我尝试了:

def home():
    form = LoginForm(request.form)
    # Handle logging in
    if request.method == 'POST':
        if form.validate_on_submit():
            login_user(form.user)
            flash("You are logged in.", 'success')
            redirect_url = request.args.get("next") or url_for("user.profile")
            return redirect(redirect_url, userobj=form.user)

我正在重定向到:

@blueprint.route("/profile")
@login_required
def profile():
    return render_extensions("users/profile.html")

我想再次将用户对象传递给 profile.html 模板。

我明白了:

TypeError: redirect() got an unexpected keyword argument 'userobj'

我该如何解决这个问题?

【问题讨论】:

  • 您似乎根本没有遵循该链接问题中的建议。首先,参数是url_for,而不是redirect;其次,答案明确指出您的目标处理程序实际上必须接受一个参数,而您的却没有。
  • 感谢您指出这一点。就我而言,我意识到我可以访问烧瓶登录的 current_user,我最终使用了

标签: python flask


【解决方案1】:

你可能做得不对。已登录的用户可通过current_user 访问,from flask.ext.login import current_user 可访问该用户

我就是这样做的

@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
    user = User.query.filter_by(email=form.email.data).first()
    if user is not None and user.verify_password(form.password.data):
        login_user(user, form.remember_me.data)
        return redirect(request.args.get('next') or url_for('main.index'))
    flash('Invalid username or password')
    return render_template('auth/login.html', form=form)

在索引视图中,我可以像模板中的 current_user.username 一样访问它

试试这个可能会有帮助

和平

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多