繁体   English   中英

如何使用Flask-WTF和Jinja2在多个页面上添加相同的登录表单作为模式?

[英]How can I add the same login form as a modal on multiple pages using Flask-WTF and Jinja2?

我想在Navbar中有一个按钮,用于打开登录表单的模式:带有电子邮件字段和密码字段的简单表单。 在模态体内,我的HTML看起来像:

<form role="form" action="/login/"method="post" name="login">
        {{ form.csrf_token }}
        {{ form.email(class_="form-control", placeholder="Email") }}
        {{ form.password(class_="form-control", placeholder="Password") }}

        <input class="form-control" type="submit" placeholder="Login"></input>
</form>

但是,Jinja2模板引擎无法识别表单,因为它未在render_template中指定:

@app.route('/')
def hello():
    return render_template('landing.html', title='Home')

有没有办法在landing.html (和其他页面)上显示表单,而不必复制每个视图的表单代码(这看起来非常低效)?

一种解决方案是编写一些javascript来进行AJAX调用以命中端点(一个新的views.py路由),它将返回呈现的HTML登录模板(模态登录对话框)。 它甚至可能是您POST的同一个端点。

在views.py中:

@app.route('/')
def hello():
    return render_template('landing.html', title='Home')


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

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        # Use werkzeug to validate user's password etc.
        if user and check_password_hash(user.password, form.password.data):
            if login_user(user):
                flash('You\'re now logged in!')
                return redirect(url_for('hello'))

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

...虽然我不能在这里提供细节(根据您的JS框架而有所不同),但您需要将Javascript添加到您的基本模板文件中,该文件将执行以下操作:

# If user not authenticated:
#    Hit /login/ via AJAX to fetch a copy of the rendered login form
#    Insert it into the DOM, presumably into the modal dialog

当未经/login/验证的用户提交表单时,它将POST到/login/ ,您需要适当的代码来处理登录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM