如何从Python Flask中的HTML select获取项目

时间:2019-05-28 09:13:07

标签: python flask

注意:

我知道我有很多问题,但我真的尝试了,但有任何成果。

我正在尝试让用户在我的端点中获得所选的选项,但是它不起作用。

我已经尝试过:

在选择html标记上写入属性名称。 在后端,我尝试了这两个选项 type_user = request.form.get('type_user')和这个 type_user = request.form['type_user']

我使用调试器模式,看到auth.py仅None并没有收到任何数据。

register.html

#I don't know if it is for the desabled attribute, if the user 
#is not logged so he cannot create a admin account only a normal account.
{% if g.user['type'] == 0 %}
        <div class="form-group">
          <label for="type_user">Type of User <span style="color: red">*</span></label>
          <select class="form-control" id="type_user" name="type_user" required>
            <option value="0">Admin</option>
            <option value="1">User</option>
          </select>
        </div>
      {% else %}
      <div class="form-group">
          <label for="type_user">Type of User <span style="color: red">*</span></label>
          <select class="form-control" id="type_user" name="type_user" required disabled>
            <option value="1">User</option>
          </select>
        </div>
      {% endif %}

auth.py

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']
        type_user = int(request.form.get('type_user'))
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')

错误:

  

第15行中的文件“ D:\ Dev \ patterns-project \ study_room \ auth.py”   寄存器         -----> type_user = request.form ['type_user'] <-----文件“ d:\ dev \ patterns-project \ my-venv \ lib \ site-         packages \ werkzeug \ datastructures.py”,第442行,位于 getitem          引发异常。BadRequestKeyError(key)

1 个答案:

答案 0 :(得分:0)

我正在简化我的答案,以便更加清楚。

register.html -无需更改。你所拥有的有效。

auth.py -需要进行细微更改。下面的if / else语句添加到您的代码中:

@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        first_name = request.form['first_name']
        last_name = request.form['last_name']

        ### Start of changed section ###
        # The line below will be None if type_user is disabled
        # type_user = int(request.form.get('type_user'))
        if "type_user" in request.form:
            # Current user must be an admin and have the option to select
            # the type_user for the new user, so read it here.
            type_user = request.form["type_user"]
        else:
            # The type_user field in the form must be disabled.
            # This means a  standard user or anonymouse person
            # must be registering a new user.  So the new user
            # must be a standard user.
            type_user = 1
        ### End of changed section ###

        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        print(type_user)
        print(first_name)
        if not (first_name and last_name and type_user and username and password):
            error = "Please fill all requiered fields"

        elif db.execute(
            'SELECT id FROM user WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (first_name, last_name, type, username, password) VALUES (?, ?, ?, ?, ?)',
                (first_name, last_name, type_user, username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')

在HTML中使用disabled的问题在于,它使<select>完全不可用。检查字典中的type_user可以处理这种情况,如下所示:

if "type_user" in request.form:
    type_user = request.form["type_user"])
else:
    type_user = 1

感谢@roganjosh指出我最初针对<div>的错误。

此处的实现:https://github.com/johnhut/flask/tree/so-q56338730