从表单数据动态路由

时间:2015-10-02 20:43:18

标签: forms flask routing wtforms

我是新手,因为从表单数据创建动态网址存在问题。具体来说,来自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中的值来生成网址。已经坚持了一段时间。表单本身和下拉列表正确显示所有内容

由于

1 个答案:

答案 0 :(得分:2)

我将表单更改为回发到其生成页面,然后从那里处理逻辑。所以改变

{{ 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)

我们正在做的就是抓住提交的内容,然后从表单元素中抓取所选的运动,然后使用该方法将用户重定向到event_select方法选择体育作为论据。