来自表单数据的动态路由

Dynamic routing from form data

我是 Flask 的新手,我在从表单数据创建动态 url 时遇到了问题。具体来自WTFORMS的一个SelectField的值。我的代码如下

我的表格是这样的

from flask_wtf import Form
from wtforms import SelectField
from wtforms.fields.html5 import DateField


class SelectEventForm(Form):
    sports = SelectField(u'Select Sport')
    start_after_date = DateField('Starts After Date')
    start_before_date = DateField('Starts Before Date')

我的控制器有以下代码

@app.route('/event', methods=['GET', 'POST'])
def event():
    form = SelectEventForm(request.form)
    sports = betfair_client.call_rest_api('listEventTypes/', {"filter": {}})
    form.sports.choices = []
    for sport in sports:
       for key in sport:
           form.sports.choices.append((key, sport[key]))
   return render_template('events.html', form=form)


@app.route('/event/<sports>', methods=['GET', 'POST'])
def event_select(sports):
    #print request.form
    #print request.form.get('sports')
    return render_template('events_two.html')

html中的表格如下

<form  class="form-style-7" action="{{ url_for('event_select',     sports=form.sports.sport) }}" method="post">
  <ul>
    <li name="sport">
      {{ form.sports.label}} {{ form.sports }}
    </li>

    <li>
      {{ form.start_after_date.label }} {{ form.start_after_date }}
    </li>
    <li>
      {{ form.start_before_date.label }} {{ form.start_before_date }}
    </li>

    &nbsp;
    &nbsp;
   <li>
    <input type="submit" value="Next">
   </li>
</ul>
</form>

我想做的是使用 SelectField 的值来生成 url。已经坚持了一段时间。表单本身和下拉列表正确显示所有内容

谢谢

我会将您的表单更改为 post 返回到它的生成页面,然后从那里处理逻辑。所以改变

{{ url_for('event_select', sports=form.sports.sport) }}

仅:

{{ url_for('event') }}

然后将您的 event 方法调整为:

from flask import redirect

@app.route('/event', methods=['GET', 'POST'])
def event():
    form = SelectEventForm(request.form)

    if form.validate_on_submit():
        chosen_sport = form.sports.data
        return redirect(url_for('event_select', sports=chosen_sport))

    sports = betfair_client.call_rest_api('listEventTypes/', {"filter": {}})
    form.sports.choices = []
    for sport in sports:
       for key in sport:
           form.sports.choices.append((key, sport[key]))
   return render_template('events.html', form=form)

我们所做的只是在提交时抓取 from,然后从表单元素中抓取选定的运动,然后使用它将用户重定向到 event_select 方法,并将选定的运动作为参数。