我正在用MongoDB作为后台数据库的一个烧瓶网站工作。我被一个我无法解决的错误所困扰。
我正在创建一个具有动态选择的水瓶WTF RadioField (从MongoDB收藏中查询,其中有住院病人的列表):
`class PatientDevConnectForm(Form):
     patient = RadioField('Select patient', 
                           choices=[], 
                           coerce=ObjectId, 
                           validators=[DataRequired()])
     submit = SubmitField("Connect")`视图函数如下所示:
def patientdev_connect():
     form = PatientDevConnectForm()
     if form.validate_on_submit():
          print("I am here")
          return render_template("home.html")
     else: 
          print(form.errors)
          print(form.patient.data)
          print(type(form.patient.data))
     pats = mongo.db.patients
     patients = pats.find()
     form.patient.choices = [(patient['_id'], patient['name']) for 
                                  patient in patients]
     return render_template("patientdev_connect.html", form=form)我的HTML是这样的:
<form method="POST" action="">
{{ form.hidden_tag() }}
 <fieldset class="form-group">
    <div class="form-group">
      Select: {{ form.patient }}
    </div>
 </fieldset>
<div class="form-group">
  {{ form.submit(class="btn btn-outliner-info") }}
</div>
我可以在没有任何问题的情况下呈现表单,也可以看到各种选择。当我单击(选择)一个RadioField选项并点击"Submit“按钮时,我得到以下indicating validate_on_submit()失败打印:
{'patient': [u'Not a valid choice']}
5b433324a02d9b4bc99a106b
<class 'bson.objectid.ObjectId'>我所面临的情况与下面的问题非常相似,但建议的解决方案对我不起作用。
发布于 2018-07-17 17:44:54
您的问题可能是这两件事之一;最简单的(但我不认为这是唯一的问题)是您的验证在验证之前不知道选择,所以尝试如下:
def patientdev_connect():
     form = PatientDevConnectForm()
     # this attaches the choices to the form before validation but may overwrite..
     pats = mongo.db.patients
     patients = pats.find()
     form.patient.choices = [(patient['_id'], patient['name']) for 
                                  patient in patients]
     if form.validate_on_submit():
          print("I am here")
          return render_template("home.html")
     else: 
          print(form.errors)
          print(form.patient.data)
          print(type(form.patient.data))
     return render_template("patientdev_connect.html", form=form)因为我评论说,仍然可能失败,没有测试,我无法确定。相反,您可能希望以这种方式构建一个动态表单:
def PatientDevConnectForm(**dynamic_kwargs):
    class PlaceholderForm(Form):
        patient = RadioField('Select patient', 
                              choices=[], 
                              coerce=ObjectId, 
                              validators=[DataRequired()])
        submit = SubmitField("Connect")
    pats = mongo.db.patients
    patients = pats.find()
    PlaceholderForm.patient.choices = [(patient['_id'], patient['name']) for 
                                  patient in patients]
    return PlaceholderForm()https://stackoverflow.com/questions/51377088
复制相似问题