[Python WTForms]如何更新SelectMultiField的choices?
有一个SelectField和一个SelectMultiField,业务需求基于SelectField的值来更新SelectMuliField的choices。
是否有办法能够在更新了SelectField之后post到server端?或者有其他的方法来更新choices?
不撸管会死星人
10 years, 2 months ago
Answers
我的做法不太优雅,但能满足你的需求。
#filename: forms.py
class ProductForm(Form):
brands = SelectField(u'brands',
choices=[],
coerce = int)
...
def __init__(self, *args, **kwargs):
super(ArticleForm, self).__init__(*args, **kwargs)
self.brands.choices = [(b.id, b.name) for b in Brand.query.all()]
class ModelForm(Form):
models = SelectMultipleField('models',
choices = [],
option_widget = widgets.CheckboxInput(),
widget = widgets.ListWidget(prefix_label = False))
views.py
# filename: views.py
@app.route('/edit')
def product_edit():
form = ProductForm()
if form.validate_on_submit():
""" request.form是一个MultiDict,request.form['models']仅仅能得到models列表的第一个元素,此处使用request.form.getlist()来获取整个列表。
"""
return render_template_string('{{data}}', request.form.getlist('models'))
return render_template('product_edit.html',form = form)
# function for Ajax
@app.route('/getmodel/<int:id>')
def model(id):
brand = Brand.query.get(id)
form = ModelForm()
if brand is not None and brand.models:
form.models.choices = [(c.id, c.name) for c in brand.models]
return render_template_string('{{ form.models(multiple=True) }}', form = form)
return u'暂无型号'
the template product_edit.html
<div>{{ form.brands }}</div>
<div id="m"></div>
<script>
$(function(){
$("#brands").change(function(){
id = $(this).val();
url = "{{ url_for('model', id=0) }}".replace("/0","/"+id)
$.get(url, function(result){
$("#m").html(result);
})
})
})
</script>
夜魅D小调
answered 10 years, 2 months ago