Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

Not a valid choice: Can't select ReferenceProperty value at SelectField wtform

i try to use ReferenceProperty at form for create/edit Entry but nothing happen.

i have:

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)

and edit handler:

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()

but i always have: Not a valid choice

Does enyone know how to work with ReferenceProperty in wtforms SelectField or may you have working sample for this?

Upvotes: 2

Views: 1420

Answers (1)

Sergey Lyapustin
Sergey Lyapustin

Reputation: 1937

I solve my problem with this changes at Form class:

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)

and edit handler:

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()

But if anyone know more elegant solution, you are welcome!

Upvotes: 1

Related Questions