【问题标题】:Append HTML Radio button options to Python Flask URL将 HTML 单选按钮选项附加到 Python Flask URL
【发布时间】:2017-08-23 17:39:02
【问题描述】:

我环顾四周,但似乎找不到答案。我有一个带有单选按钮选项的 html 表单。当根据 html 页面上的用户输入发布结果时,我正在尝试将它们附加到烧瓶 url。

这是我的 html 页面:

<form class="form-search" id="formdata" action="{{url_for('users')}}" method="post">
    <label><font size="4">Select option:</font></label>
    <div class="labeltext btn-group" data-toggle="buttons">
       <label class="btn btn-primary active">
          <input type="radio" name="radioOptions" id="option1" value="Option1" checked> Option1 </label>
       <label class="btn btn-primary">
          <input type="radio" name="radioOptions" id="Option2" value="Option2"> Option2 </label>
    </div>
</form>

我的 Flask 视图:

@app.route('/users/<selectOption>', methods=['GET', 'POST'])
def users(selectOption):
    if request.method == 'POST':
      radioOptions = request.form['radioOptions']
     return redirect (url_for('users', selectOption=selectOption))
return render_template('users.html')

我遇到了错误

TypeError: users() 只接受 1 个参数(给定 0)

不确定我到底出了什么问题。我正在尝试使我的网址如下所示:

localhost:8080/users?radioOptions=Option1

【问题讨论】:

    标签: python html flask


    【解决方案1】:
    TypeError: users() takes exactly 1 argument (0 given)
    

    您收到的上述错误说明了一切。在以下代码中:

    if request.method == 'POST':
          radioOptions = request.form['radioOptions']
         return redirect (url_for('users', selectOption=selectOption))  
    

    您在提交单选选项时重定向到 usersusers 需要一个您尚未提供的参数,即它是可变的,这就是您收到此错误的原因。另外,您也不使用您从该行检索到的 radioOptions 值

    selectOption = request.form['radioOptions']  #I have changed radioOptions to selectOption
    

    正确和更简洁的方法是定义另一个函数来呈现您的模板,然后在您的重定向调用中调用它,如下所示:

    @app.route('/users', methods=['GET', 'POST'])
    def users():
        if request.method == 'POST':
          selectOption = request.form['radioOptions']
         return redirect (url_for('call_selected', selectOption=selectOption))
        return render_template('users.html')
    
    
    @app.route('/<selectOption>', methods=['GET', 'POST'])
    def call_selected(selectOption):
        return render_template(selectOption)
    

    【讨论】:

    • 感谢您提供最合适的答案。我想我能够理解出了什么问题。但我到底想要实现的是一个如下的网址:users?radioOptions=option1&amp; .. so on 但是当我总是以这样的网址结束时:users/option1 有错误。试图再次解决这个问题。
    • 看来您正在尝试将参数作为查询字符串传递。这仅在 GET 请求中才有可能。 POST 不显示作为查询字符串传递的参数。
    • @Ray 有帮助吗?你的问题解决了吗?
    • 是的,如果我用新的 html 页面创建一个新函数,它就可以工作。但是如果我尝试调整现有代码,结果是不利的。试图找出实现这一点的最佳方法。谢谢你:)
    • 感谢 @0decimal0 帮助我解决这个问题。我能够解决这个问题。当然,我明白这为时已晚,但由于额外的责任和优先事项,我无法抽出时间来完成这项任务。
    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2021-07-17
    • 1970-01-01
    • 2013-02-05
    相关资源
    最近更新 更多