【问题标题】:store form info in jinja framework在 jinja 框架中存储表单信息
【发布时间】:2018-12-25 15:50:15
【问题描述】:

我正在python烧瓶框架中开发产品推荐系统。

现在这个 display_recommendations.html 将显示算法从数据库中选择的“最佳”10 个产品。在用户通过选中 html 表单中的复选框做出选择后,我希望我可以在此 html 模板中存储一个变量,然后将其传递给 submit_choices(),这是用户单击“提交我的选择并播放”时的事件处理程序再来一轮!”按钮

submit_choices() 函数然后会更新数据库(调整置信度分数,更新用户偏好等)

{% extends 'layout.html' %}

{% block body %}
<h1> Welcome {{session.username}}! </h1>
<h4>You can select the pillows you like and the ones you don't, after that, hit submit, or return to dashboard</h4>
<hr>
<form action="" method="post">
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Price</th>
<th>Image</th>
<th></th>
<th></th>

</tr>
{% set likes = '100' %}
<!-- {% set nopes = [] %} -->
{% for pic in pictures %}
  <tr>
    <td>{{pic.idx}}</td>
    <td>{{pic.price}}</td>
    <td><img src = {{pic.img}} width = "350"></td>

    <td>
      <!-- <form action="" method="post"> -->
        <input type="checkbox" id="like" class="btn btn-success" name = "like" class="form-control" value= {{pic.idx}}>
        <label for="like">I like it!</label>
      <!-- </form> -->
    </td>


    <td>
      <!-- <form action="" method="post"> -->
        <input type="checkbox" id="nope" class="btn btn-danger"  name = "nope" class="form-control" value={{pic.idx}}>
        <label for="nope">Nope</label>
      <!-- </form> -->
    </td>


  </tr>
{% endfor %}

</table>
</form>

<form action="{{url_for('submit_choices',choices= [likes,nopes])}}">
<input type="submit" value="Submit my choices and Play Another Round!" class="btn btn-danger">

</form>

{% endblock %}

【问题讨论】:

  • “在这个 html 模板中存储一个变量”是什么意思?您希望将表单数据提交给 submit_choices() 事件处理程序吗?您需要将复选框和提交按钮放在 1 个表单中,而不是像以前那样放在 3 个表单中,并且只需像现在一样将按钮放在表单中。

标签: html web flask web-applications jinja2


【解决方案1】:

首先你必须按照@lciamp 所说的去做。对于 Jinja2 部分,我会将 &lt;form action="{{url_for('submit_choices',choices= [likes,nopes])}}"&gt; 替换为 &lt;form action="https://[rest of URL]/[abc]" method="post"&gt;

&lt;label for="like"&gt;I like it!&lt;/label&gt; 需要更改,like 只能用于一个(它们必须是唯一的,因为这是服务器检查每个字段的方式)。

那么,假设submit_choices()在服务器上的Python中,你应该添加一个@app.route装饰器。

示例([abc] 是您在顶部写的):

@app.route('/[abc]', methods=['POST'])
def submit_choices():
    #Whatever you put here
    #To access the form data use:
    request.values.get('[whatever comes after the "for" in the label]')

如果您有任何问题,请联系here

希望我能帮上忙。

【讨论】:

    【解决方案2】:

    您需要将复选框和提交按钮全部放在 1 个表单中:

    <form>
        <input type="checkbox">
        <input type="checkbox"> 
        <input type="submit">
    </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多