I'm trying to create an AddtoCart and Checkout functionality using python flask and flask-sqlalchemy. I consider myself to be a beginner at web development in general. How do I take a product item and add it to a cart as a cart item using a button? I would also like to calculate the total price of cart items.
So far I created two models (ProductItem,CartItem). I created successfuly 2 ProductItems (dummy data) and was able to display them in a view using a for loop with jinja2 template. I've tried to create a function to select the product and add it to the cart but I couldn't figure out the way on how to make the add to cart button functionality work.
Thanks in advance!!
class ProductItem(db.Model):
__tablename__='products'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
descr = db.Column(db.Text,unique=True,nullable=True)
price = db.Column(db.Float,nullable=False)
img = db.Column(db.String(64),unique=True)
cartitems = db.relationship('CartItem', backref='Product')
def __repr__(self):
return '<ProductName %r>' % self.name
class CartItem(db.Model):
__tablename__='cartitems'
id = db.Column(db.Integer,primary_key=True)
# adding the foreign key
product_id = db.Column(db.Integer, db.ForeignKey('products.id'))
@app.route('/')
def index():
products = Product.query.all()
return render_template('home.html',products=products)
def getproductitem():
itemid = product.id
productname = product.name
productname = CartItem(product_id=itemid)
db.session.add(product)
db.session.commit()
----------------html jinja----------
{% for product in products %}
<div class="product-item">
<h3>{{ product.name }}</h3>
<img src="static/img/products/{{ product.img }}" alt="" width="200px" height="200px">
<p> {{ product.price }}</p>
<button onclick="getproductitem()" type="button" class="btn btn-primary">Add to Cart</button>
</div>
{% endfor %}