【问题标题】:How to implement select so that I can access selelected value in my code when user clicks submit button如何实现选择,以便当用户单击提交按钮时我可以访问代码中的选定值
【发布时间】:2014-08-12 00:27:48
【问题描述】:

我正在制作基于 Flask documentation 的简单上传器,从获取文件到保存文件,一切正常。我的问题是如何实现选择,以便当用户单击提交按钮时我可以访问代码中的选定值,最好用户必须选择其中一个值。

在模板中

        <div>
          <form action="upload" method="post" enctype="multipart/form-data">

            <div style="position:relative; overflow:hidden;">
            <a class='btn btn-primary' href='javascript:;'>
                Choose document
                <input type="file" style='position: absolute;top: 0;right: 0;min-width: 100%;min-height: 100%;font-size: 999px;
                text-align: right;filter: alpha(opacity=0);opacity: 0;outline: none;background: white;cursor: inherit;display: block;' 
                name="file" id ="Mfile" size="40" onchange='$("#upload-file-info").html($(this).val());'>
            </a>
            &nbsp;
            <span class='label label-info' id="upload-file-info"></span>
        </div>
        <br/>
    <br/>
    <select name = "choose" class="form-control">
      <option value="cop">Computer programming</option>
      <option value="bio">Biology</option>
      <option value="mth">Math</option>
      <option value="soc">Sociology</option>
      <option value="psy">Psychology </option>
    </select>
    <br/>
            <button type="submit" class="btn btn-success">
                <i class="icon-circle-arrow-right icon-large"></i> Submit
            </button>
      </form>
      </div>

在代码中

@main.route('/upload', methods=['POST'])
@login_required
def upload():
    file = request.files['file']
    ...
    ...

【问题讨论】:

  • 你见过the documention on the request object吗?如果是这样,有什么不清楚的地方(提示request.form['choose'])?
  • 谢谢,问题已解决,能否请您以正式的方式发布,以便我接受它作为答案。

标签: jquery python html python-2.7 flask


【解决方案1】:

要访问 Flask 中任何用户提供的值,您可以使用 request objectrequest 是一个与请求上下文相关联的线程本地,您可以使用它来访问:

  • 通过request.args 查询字符串参数(例如/some/url?these=params&amp;right=here

    request.args['these']  # "params"
    request.args['right']  # "here"
    
  • 来自表单帖子等的 URL 编码的正文参数,通过request.form

    <!-- in your html -->
    <form action="/do-stuff" method="post">
        <input name="these" value="params">
        <input name="right" value="here">
        <input type="submit">
    </form>
    
    
    # In your script
    request.form['these']  # "params"
    request.form['right']  # "here"
    
  • JSON 编码的正文通过request.get_json(),cookie 数据通过request.cookies 等等(详细信息在the API documentation for flask.Request

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多