如何在FlaskWTF表格中组合不同的字段类型

2024-09-20 23:04:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用flask wtf表单构建表单。我有一个字段,用户可以在其中选择多个选项。如果他们想要的选择不在我的名单上。我想允许用户选择“其他”并通过文本字段指定他们的选项

我找不到办法在wtforms中这样做。我在谷歌上搜索过,似乎在任何地方都找不到答案。我所做的绝不是一个独特的场景,我会想象这是非常普遍的。所以我想我可能是想错了

question1_options = [('rice','rice'),('chips','chips'),('tuna','tuna'), ('other', 'other')]
question2_options = [('yes', 'yes'),('no', 'no')]

class MyForm(FlaskForm):
    q1 = SelectMultipleField('favourite food?', choices=question1_options)
    q2 = RadioField('do you like football', choices=question2_options)

我想要实现的目标:

将SelectMultipleField与StringField组合,以便在列表中没有相应选项时使用。用户可以选择其他并输入他们想要的内容


Tags: no用户flask表单选项yeschoicesoptions
1条回答
网友
1楼 · 发布于 2024-09-20 23:04:41

我找不到合并两个字段的方法

我认为它应该是两个始终可见的分离字段

q1_options = [('rice','rice'),('chips','chips'),('tuna','tuna')] #, ('other', 'other')]

class MyForm(FlaskForm):
    q1 = SelectMultipleField('Favourite food?', choices=q1_options)
    q1_other = StringField('Other favourite food?')

或者,当您选择other时,它应该使用JavaScript来显示StringField

我试图创建最小的工作代码

因为它使用multiple select,所以需要更复杂的JavaScript代码

from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, StringField, RadioField
from wtforms.validators import DataRequired, Optional

#  - form  -

q1_options = [('rice','rice'),('chips','chips'),('tuna','tuna'), ('other', 'other')]

class MyForm(FlaskForm):
    q1_list  = SelectMultipleField('Favourite food?', choices=q1_options, validators=[DataRequired()])
    q1_other = StringField('Other', validators=[Optional()])

#  - app  -

app = Flask(__name__)
app.config['SECRET_KEY'] = 'qwerty123456'

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()
    #print(dir(form))
    print(form.validate_on_submit())
    #if form.validate_on_submit():
    if form.is_submitted():
        print('list:', form.q1_list.data)
        print('other:', form.q1_other.data)

    return render_template_string('''<!DOCTYPE html>    
<html>
<head>
<meta charset="utf-8">
</head>
<body>    

<form method="POST">
    {{ form.q1_list.label }}<br>
        {{ form.q1_list(onchange="get_selection(this);") }}<br>
        {{ form.q1_other(style="display:none") }}<br>
    <input type="submit" value="Go">
</form>

<script language="javascript">
//var q1_list  = document.querySelector("#q1_list");
var q1_other = document.querySelector("#q1_other");

function get_selection(select){
  //console.log(select);
  //console.log(select.value);
  //console.log(select.options);

  var opts = [];
  var opt;    
  
  var len = select.options.length;
  
  for(var i = 0; i < len; i++) {
    opt = select.options[i];

    if (opt.selected) {
      opts.push(opt.value);
    }
  }    
  
  //console.log(opts);
  
  if(opts.includes('other')){
    q1_other.style.display = 'block';
  }else{
    q1_other.style.display = 'none';
  }
}
</script>

</body>
</html>
''', form=form)

#  - start  -

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

addEventListener相同,而不是onchange

<form method="POST">
    {{ form.q1_list.label }}<br>
        {{ form.q1_list() }}<br>
        {{ form.q1_other(style="display:none") }}<br>
    <input type="submit" value="Go">
</form>

<script language="javascript">
//var q1_list  = document.querySelector("#q1_list");
var q1_other = document.querySelector("#q1_other");

q1_list.addEventListener('input', function(event) {
  //console.log(event);
  //console.log(event.target.value);
  //console.log(event.target.options);

  var select = event.target;
  
  //console.log(select.options);

  var opts=[];
  var opt;    
  
  var len = select.options.length;
  
  for(var i = 0; i < len; i++) {
    opt = select.options[i];

    if (opt.selected) {
      opts.push(opt.value);
    }
  }    
  
  //console.log(opts);
  
  if(opts.includes('other')){
    q1_other.style.display = 'block';
  }else{
    q1_other.style.display = 'none';
  }
}, false);
</script>

相关问题 更多 >

    热门问题