Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Items to Shopping Cart Python Flask

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 %}
like image 762
Costas Nicou Avatar asked Mar 20 '26 07:03

Costas Nicou


1 Answers

Edit

Realised I didn't answer the question about the button. Seems like you're trying to call you python function from the html (unless you have a javascript function also in your front end template).

Your python lives on the server and your html/javascript will be on the client browser - you need to make them communicate by sending a HTTP request from your page to the server, you can't call functions directly.

Server:

@app.route('/cart/<int:product_id>', methods=['POST'])
def add_to_cart(product_id):

    product = Product.query.filter(Product.id == product_id)
    cart_item = CartItem(product=product)
    db.session.add(cart_item)
    db.session.commit()

    return render_tempate('home.html', product=products)

add to your html:

<script>
function addToCart(productId) {
    fetch('[your.local.host.]/cart/productId', 
        {method: 'POST'}
    )
}
</script>

change the button:

<button onclick="addToCart({{product.id}})" type="button" class="btn btn-primary">Add to Cart</button>

Or something similar. Your page needs to talk to your server via HTTP requests.

Original answer about carts

It's probably not necessary to persist your cart in the database unless you really want your users to be able to access the same cart when logging in across devices, or you anticipate they will need to keep items there more long term.

Persisting will add unnecessary time to user requests (while you add/retrieve them) and that CartItem table will continue to get larger and larger and most rows will become redundant (unlikely people want to view their old shopping cart once they've bought products). One solution would be to also link the carts to a User table so you only have one cart per user (provided your users are logged in when shopping), or make sure you delete carts once they're bought or after a certain time period.

However, if you have no need to persist longer term, consider storing the product ids either in either

  1. The flask session. Essentially a lightweight, in memory store on the server that is linked to a user and can be accessed during the request handling. See a tutorial on sessions here.

  2. Inside a cookie. A cookie is stored in the browser (not the server) and usually signed with a key. This does not make them secure - it just means you can be sure no one has modified its content when you retrieve it on the server. See a tutorial here.

This article discusses a few drawbacks/merits to both approaches.

like image 123
elembie Avatar answered Mar 22 '26 00:03

elembie