WTForm: how do I tell Form to use a custom method for one particular attribute?

余生长醉 提交于 2019-12-11 05:29:57

问题


I have the following definitions:

class ProduceType(ndb.Model):
  crop = ndb.StringProperty()
  variety = ndb.StringProperty()

class OrderEntry(ndb.Model):
  producetype = ndb.KeyProperty(kind=ProduceType, required=True)
  quantity = ndb.IntegerProperty(required=True)

I created the following WTForm:

class OrderEntryForm(Form):
  quantity = IntegerField('Quantity',
                          [validators.Required(), validators.NumberRange(min=1)])
  # we will be dynamically adding choices
  producetype = SelectField('Produce',
                            [validators.Required()],
                            choices=[])

This is what I am doing in my tests:

def setUp(self):
  self.pt1 = ProduceType(crop='Choi', variety='Bok')
  self.pt2 = ProduceType(crop='Cress', variety='True')
  self.pt1.put()
  self.pt2.put()

def test_order_entry(self):
  oe = OrderEntry(producetype=self.pt1.key, quantity=20)
  oef = OrderEntryForm(obj=oe)
  oef.producetype.choices = [
      (self.pt1.key.id(), self.pt1.name()),
      (self.pt2.key.id(), self.pt2.name())
  ]
  print oef.producetype

And this is what's being printed:

<select id="producetype" name="producetype"><option value="1">Choi - Bok</option><option value="2">Cress - True</option></select>

Problem: I am trying to render the form for my users to edit.

So if an OrderEntry in my database looks likes:

order_entry = { producetype: self.pt1.key, quantity: 5 } 

I would expect WTForms to be rendering something like:

<select id="producetype" name="producetype">
  <option value="1" selected>Choi - Bok</option>
  <option value="2">Cress - True</option>
</select>

However, right now I cannot get WTForm to render the selected properly. The select being rendered is currently empty.

How do I get WTForm to render selected correctly?

NOTE:

During form population, i.e. oef = OrderEntryForm(obj=oe), if WTForm tries to access obj.producetype, that will give you a ndb.key. As you can see, the first member of the oef.producetype.choices tuple is of ndb.key.id() as opposed to ndb.key

来源:https://stackoverflow.com/questions/24324161/wtform-how-do-i-tell-form-to-use-a-custom-method-for-one-particular-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!