【问题标题】:Not a valid choice: Can't select ReferenceProperty value at SelectField wtform不是一个有效的选择:无法在 SelectField wtform 处选择 ReferenceProperty 值
【发布时间】:2011-06-21 13:38:27
【问题描述】:

我尝试在表单中使用 ReferenceProperty 来创建/编辑条目,但没有任何反应。

我有:

class Type(db.Model):
    name        = db.StringProperty()



class Entry(db.Model):
    type            = db.ReferenceProperty(Type, required=False)

class EntryForm(Form):
    _type_list = []
    for type in Type.all():
        _type_list.append((type.key(),type.name))
    type            = fields.SelectField(u'Type of entry', choices = _type_list)

和编辑处理程序:

def post(self, **kwargs):
    self.form = EntryForm(self.request.form)
    if self.form.validate():
        values = {
            'type': models.Type.get_by_key_name(self.form.type.data).key(),
        }
        entry = Entry(**values)
        entry.put()

但我总是有:不是一个有效的选择

是否有人知道如何在 wtforms SelectField 中使用 ReferenceProperty,或者您是否有这方面的工作示例?

【问题讨论】:

  • 你在哪一行得到这个错误?
  • 所以你可能会在 if 语句中得到它。选项显示是否正确,您是否选择了一个?如果字段数据不是可能选择的一部分,则 SelectField.pre_validate 似乎会引发异常。 (code.google.com/p/tipfy/source/browse/source/lib/wtforms/…)
  • 当我尝试保存选定的值时,我在表单验证时有“无效的选择”。是的值正确显示。

标签: python google-app-engine tipfy wtforms


【解决方案1】:

我通过 Form 类的这些更改解决了我的问题:

class EntryForm(Form):
    _type_list = []
    for type in Type.all():
        _type_list.append((type.key().id(),type.name))
    type            = fields.SelectField(u'Type of entry', choices = _type_list, coerce=int)

和编辑处理程序:

def post(self, **kwargs):
    self.form = EntryForm(self.request.form)
    if self.form.validate():
        values = {
            'type': models.Type.get_by_id(self.form.type.data),
        }
        entry = Entry(**values)
        entry.put()

但如果有人知道更优雅的解决方案,欢迎您!

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2019-01-14
    • 2021-01-25
    • 2018-06-11
    相关资源
    最近更新 更多