问题
In my application, a 'set' can have a number of 'products' associated with it. Products listed against a set must have quantities defined. For this many-to-many relationship I have followed the SQLAlchemy documentation to use an association table with an additional column (quantity
).
With the code included below, I am able to successfully update existing (manually entered) data in my tables using a form generated with Flask-WTF, but I am not able to add a new 'association'. I receive the following error:
TypeError: populate_obj: cannot find a value to populate from the
provided obj or input data/defaults
I suspect, it's because python cannot locate/doesn't have a value for set_id
. When I print(form.data)
, I see the following output:
'products': [{'product_id': 1, 'quantity': '105', 'csrf_token': '...'}, {'product_id': 2, 'quantity': '123', 'csrf_token': '...'}, {'product_id': 4, 'quantity': '120', 'csrf_token': '..'}]
Do you agree that the lack of reference to the set.id
might be the problem? I tried including a set.id
field in the main form class SetForm()
, but that didn't work. Is there a way to pass this to populate_obj()
somehow or should I be doing this 'manually' by iterating over the form data like so?:
for item in form.products.entries:
product = Product.query.filter_by(id=item.data['product_id'])
set = Set.query.get(id)
association = Set_Product_Association(set=set, product=product, quantity=data['quantity']
db.session.add(association)
Here are (hopefully) the relevant bits of code:
forms.py
class SetProdForm(FlaskForm):
product_id = SelectField('Product', coerce=int)
quantity = TextField()
def __init__(self, *args, **kwargs):
super(SetProdForm, self).__init__(*args, **kwargs)
self.product_id.choices = [(product_id.id, product_id.part_number)
for product_id in Product.query.order_by(Product.part_number).all()]
class SetForm(FlaskForm):
...
products = FieldList(FormField(SetProdForm), min_entries=3)
submit = SubmitField('Update')
models.py
class Set_Product_Association(db.Model):
__tablename__ = 'set_product_association'
set_id = db.Column(db.Integer, db.ForeignKey('sets.id'), primary_key=True)
product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True)
quantity = db.Column(db.Integer)
product = db.relationship("Product", back_populates="sets")
set = db.relationship("Set", back_populates="products")
class Set(db.Model):
__tablename__ = 'sets'
id = db.Column(db.Integer, primary_key=True)
products = db.relationship("Set_Product_Association",
back_populates="set")
class Product(db.Model):
__tablename__= 'products'
id = db.Column(db.Integer, primary_key=True)
part_number = db.Column(db.String(100), unique=True, nullable=False)
sets = db.relationship("Set_Product_Association",
back_populates="product")
views.py
@main.route('/sets/edit/<int:id>', methods = ['GET', 'POST'])
@login_required
def editSet(id):
setToBeEdited = Set.query.get_or_404(id)
form = SetForm(obj=setToBeEdited)
if form.validate_on_submit():
form.populate_obj(setToBeEdited)
db.session.add(setToBeEdited)
db.session.commit()
flash('Set definition has been updated.')
return redirect(url_for('.sets'))
return render_template('edit_set.html', form=form)
来源:https://stackoverflow.com/questions/56319689/using-wtforms-populate-obj-to-update-many-to-many-association-table-with-extra-c