Flask Python提交按钮

时间:2014-12-10 21:13:40

标签: python html twitter-bootstrap flask

我正在尝试创建一个注册用户的页面,但我的bootstrap表单中的提交按钮不起作用。当我点击提交按钮时,我收到错误的请求错误。这是我的python文件中的代码:

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email'] or '@' not in request.form['email']:
            error = 'You have to enter a valid email address'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif get_user_id(request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            print(request.form['username'])
            db = get_db()
            db.execute('INSERT INTO user (username, email, pw_hash) VALUES (?, ?, ?)',
                       [request.form['username'], request.form['email'],
                        generate_password_hash(request.form['password'])])
            db.commit()
            flash('You were successfully registered and can login now')
            return render_template('control.html')
    return render_template('register.html')

我也有一个html文件register.html:

{% extends 'layout.html' %}
{% block title %}Sign-up{% endblock title %}
{% block body %}
<div class="container">
    <form class="form-register" role="form" method="post" action="{{ url_for('register') }}">
        <h2 class="form-register-heading">Please sign up</h2>
        <label for="username" class="sr-only">Username</label>
        <input type="username" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>
        <label for="email" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" class="form-control" value="{{ request.form.email }}" placeholder="Email address" required autofocus>
        <label for="password" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required >
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
    </form>

</div>
{% endblock body %}

我无法找到错误的地方,我是python和flask的新手!

1 个答案:

答案 0 :(得分:2)

您的input字段没有name属性。这将导致您的所有检查都生成KeyError s。第一步是将属性添加到每个输入。

<input name="username" type="text" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>

请注意,我还检查了type属性,因为没有username类型。 emailpassword是有效值,在HTML5中添加了email

下一步将是更改您检查字段的方式。如果您只关心字段的存在,in是可行的方法。

if 'username' not in request.form:

但是,如果您还想要一个truty值,那么get方法就是你想要的。

if not request.form.get('username'):