烧瓶wtforms在动态selectField中提交问题

时间:2019-12-07 07:17:35

标签: python flask wtforms

我是不熟悉烧瓶的人,试图用wtforms构建一个简单的动态selectField。 我的表单有两个selectField state&city。借助于js,我正在将city field wrt动态更新为state字段选择。 但是,每次我提交表单时,都会在“ form.validation_on_submit()”上收到错误“无效选择”。 我已经做了很多RND并在互联网上进行搜索,但找不到合适的解决方案。    任何帮助将不胜感激。预先感谢。

version:[python 2.7,Flask 1.1.1,WTForms 2.2.1]

/app.py

from flask import Flask, render_template, jsonify
from wtforms import SelectField, SubmitField
from flask_wtf import FlaskForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is a secret key'
data = {
'Maharashtra':['Mumbai','Pune','NaviMumbai'],
'Gujarat':['Ahemdabad','Gandhinagar','Vadodara']
}

class MyForm(FlaskForm):
    state = SelectField('State',choices=[])
    city = SelectField('City',choices=[])
    submit = SubmitField('Submit')

@app.route('/',methods=['GET','POST'])
def index():
    form = MyForm()
    form.state.choices = zip(data,data)

    if form.validate_on_submit():
        return '<h1>Selected State : {}, City : {}</h1>'.format(form.state.data,form.city.data)
    return render_template('index.html',form=form)

@app.route('/city/<string:state>')
def get_cities(state):
    return jsonify(data[state])

if __name__ =='__main__':
    app.run(debug=True)

/templates/index.html

<!DOCTYPE html>
<body>
    <form method="POST">
        {{ form.csrf_token }}
        <div>{{ form.state }}</div>
        <div>{{ form.state.errors}}</div>
        <div>{{ form.city }}</div>
        <div>{{ form.city.errors}}</div>
        <div>{{ form.submit }}</div>
    </form>
    <script type="text/javascript">
        let state_select = document.getElementById('state');
        let city_select = document.getElementById('city');
        state_select.onclick = function(){
            state = state_select.value;
            fetch('/city/'+state).then(function(response){
                response.json().then(function(data){
                    let optionsHTML ="";
                    for(let index in data){
                        optionsHTML += "<option value="+ data[index] +">"+ data[index] +"</option>"
                    }
                    city_select.innerHTML = optionsHTML;
                });
            });
        }
    </script>
</body>
</html>

0 个答案:

没有答案
相关问题