Reputation:
so...
This:
model_dictionary = model.as_dict() # some kind of dictionary
form = TheModelsForm(**model_dictionary) # https://wtforms-alchemy.readthedocs.io/en/latest/advanced.html
form.populate_obj(model)
return form
This let's me pre populate the model's form with fields from the model that are db.Columns.. Well.. what about db.relationships on the model?
The above code is not pre-populating the relationship fields; they show up but are left blank. Only the db.Column fields are pre-populated with values regardless of whether I force include the relationship values in the model_dictonary or not (for example, model_dictionary['key_from_other_object'] = associated value).
Can this be accomplished? --Can't find anything on this..
Edit: I solved my initial problem with:
form = TheModelsForm(obj=model)
form.populate_obj(model)
return form
Now I'm trying to figure out how to get the events on the location's model to actually show up on the Location form...
class Event(Base):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
class Location(Base):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String())
events = db.relationship('Event', backref=db.backref('events'))
I'm sure there is a logical reason why all the stuff I commented out isn't working.. I'm getting 'NoneType' object is not iterable
class EventForm(ModelForm):
class Meta:
model = models.Event
location_id = fields.SelectField(u'Location', coerce=int)
class LocationForm(ModelForm):
class Meta:
model = models.Location
#events = fields.SelectField(u'Event', choices=[(g.id, g.selector) for g in models.Event.query.all()], coerce=int)
# events = fields.SelectMultipleField('Event',
# choices=[(g.id, g.selector) for g in models.Event.query.all()],
# coerce=int,
# option_widget=widgets.CheckboxInput(),
# widget=widgets.ListWidget(prefix_label=False)
# )
#events = ModelFieldList(fields.FormField(EventForm))
Upvotes: 1
Views: 1346
Reputation:
was barking up the wrong tree using SelectMultipleField and SelectField..
Instead,
wtforms_alchemy.fields.QuerySelectMultipleField
@ https://media.readthedocs.org/pdf/wtforms-alchemy/latest/wtforms-alchemy.pdf
and
this post, which helped to show usage, @ WTForms QuerySelectMultipleField Not sending List
solved my problem..
..ended up with
class LocationForm(ModelForm):
class Meta:
model = models.Location
events = wtforms_alchemy.fields.QuerySelectMultipleField('Event',
query_factory=lambda: models.Event.query.order_by(models.Event.name).all(),
get_label= lambda x: x.name,
option_widget=widgets.CheckboxInput(),
widget=widgets.ListWidget(prefix_label=False)
)
Upvotes: 2