I am trying to get the data from the Form and Post it to the database using SQLAlchemy I have a relation ship to Category and Brand Models as shown in the Product model. But i am getting an error:
AttributeError: 'int' object has no attribute '_sa_instance_state'
I am not sure but i think is what is being returned is a Category() object and i have to pass and id to the instantiated Product() object
What could be wrong here ?
model
class Product(db.Model):
# Table name
__tablename__ = 'products'
# Main Fields
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255), nullable=False)
slug = db.Column(db.String(255), nullable=False, unique=True)
description = db.Column(db.Text(255), nullable=True)
active = db.Column(db.Boolean)
# Timestamps
created = db.Column(db.DateTime(), default=datetime.utcnow)
updated = db.Column(db.DateTime(), default=datetime.utcnow,
onupdate=datetime.now)
# ForeignKeys
category_id = db.Column(db.Integer, db.ForeignKey('categories.id'))
brand_id = db.Column(db.Integer, db.ForeignKey('brands.id'))
# Backref Relations
category = db.relationship('Category', backref='products')
brand = db.relationship('Brand', backref='products')
def __repr__(self):
return self.name
def __unicode__(self):
return self.name
form
class ProductForm(Form):
name = StringField('Name', validators=[Required(), Length(1, 255)])
slug = StringField('Slug', validators=[Required(), Length(1, 255)])
description = StringField('Description', validators=[Required(), Length(1, 255)])
active = BooleanField('Active')
category = SelectField('Category', coerce=int)
brand = SelectField('Brand', coerce=int)
submit = SubmitField('Add Product')
view
@inventory.route('/product/new/', methods=['GET', 'POST'])
def add_product():
form = ProductForm()
categories = [(c.id, c.name) for c in Category.query.all()]
brands = [(b.id, b.name) for b in Brand.query.all()]
form.category.choices = categories
form.brand.choices = brands
if form.validate_on_submit():
new_product = Product(name=form.name.data,
slug=form.slug.data,
description=form.description.data,
active=form.active.data,
category=form.category.data,
brand=form.brand.data)
db.session.add(new_product)
db.session.commit()
flash('New Product has been added')
return redirect(url_for('inventory.list_products'))
return render_template('inventory/form.html', form=form)