繁体   English   中英

将 flask 表单字段与 html 输入相结合

[英]Combine flask form field with html input

我有一个 FieldList 表单,允许用户输入他们旅行路线的起点和终点。

我正在尝试添加 Google 的自动完成 API 以使用户更容易在字段中输入地址。

forms.py

from flask_wtf import Form
from wtforms import (
  StringField,
  FormField,
  FieldList
)
from wtforms.validators import (
  Length,
  Optional
)


class RouteForm(Form):
    origin = StringField([Optional(),  Length(1, 256)])
    destination = StringField([Optional(),  Length(1, 256)])


class JourneysForm(Form):
    ids = []
    journeys = FieldList(FormField(RouteForm))

编辑.html


{% import 'macros/form.html' as f with context %}

<tbody>
    <tr>
    {% for journey, route in zip(form.journeys, routes) %}
      <td>
        {% call f.location_search(journey.origin,
                            css_class='sm-margin-bottom hide-label') %}
        {% endcall %}
      </td>
    </tr>
    {% endfor %}
</tbody>


<div class="col-md-6">
  <button type="submit" class="btn btn-primary btn-block">
      'Save'
  </button>
</div>

宏/表单.html


<head>

    <script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=<KEY>&callback=initMap" async defer></script>
    
    <script>
      function initMap() {
          var input = document.getElementById('searchInput');
          var autocomplete = new google.maps.places.Autocomplete(input);
      }
    </script>
    
</head>


{# Render a form for searching a location. #}
{%- macro location_search(form, css_class='') -%}
    <input type="text" class="form-control"
            id="searchInput" placeholder="Enter location">
  {{ form(class=css_class, **kwargs) }}
  {{ caller () }}
{%- endmacro -%}

路线.py

@route('/edit', methods=['GET', 'POST'])
def routes_edit():

    routes = get_routes()
    journeys_form = JourneysForm()

    if journeys_form.validate_on_submit():
        for i, entry in enumerate(journeys_form.journeys.entries):

            origin = entry.data['origin']

但是,这会呈现两个字段。 一种包含 Google 自动完成输入,但不提交值(顶部)。 另一个没有 Google 自动完成输入但通过 routes.py (底部)将值提交给数据库的字段。

形式

是否可以将其组合成一个既包含 Google 自动完成功能又将输入值提交给数据库的字段?

WTForms 实际上呈现一个输入 class 本身:

<input class="form-control" id="journeys-0-origin" name="journeys-0-origin" type="text" value="" placeholder="Enter a location" autocomplete="off">

因此,我不必要地复制了输入元素。 为了让 Google 自动完成功能正常工作,我只需将输入 id 传递到我的 js function 中:

      function initMap() {
          var input = document.getElementById('journeys-0-origin');
          var autocomplete = new google.maps.places.Autocomplete(input);
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM