Implementing Basic Add to Cart Functionality in Python Using Flask

In e-commerce websites, the "Add to Cart" feature allows users to select products they want to purchase and store them temporarily while they continue shopping. Implementing this functionality in a web application using Python and Flask is straightforward and can be done with a few simple steps.

 

python flask add to cart

 

 

Setting Up the Project:


First, create a new directory for your project and set up a virtual environment to manage dependencies. Install Flask using pip and create three main files: `app.py`, `index.html`, and `cart.html`.

 

Read also:
 

 

 

Creating HTML Templates:


Create HTML templates for displaying products (`index.html`) and the shopping cart (`cart.html`). These templates will use Bootstrap for styling and will be rendered by Flask.




index.html



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Products</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5">Products</h1>
<div class="row mt-4">
{% for product in products %}
<div class="col-md-3">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ product['name'] }}</h5>
<p class="card-text">Price: ${{ product['price'] }}</p>
<form action="/add_to_cart" method="post">
<input type="hidden" name="product_id" value="{{ product['id'] }}">
<button type="submit" class="btn btn-primary">Add to Cart</button>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
  
  




add to cart in python using flask

 

cart.html



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cart</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5">Shopping Cart</h1>
<ul class="list-group mt-4">
{% for item in cart %}
<li class="list-group-item">
<div class="d-flex justify-content-between align-items-center">
<h5>{{ item['name'] }}</h5>
<span class="badge badge-primary badge-pill">${{ item['price'] }}</span>
</div>
</li>
{% endfor %}
</ul>
<a href="/" class="btn btn-primary mt-4">Continue Shopping</a>
</div>
</body>
</html>



 
add to cart in python using flask



 

Writing Python Code:


In `app.py`, import Flask and other necessary modules. Define routes for rendering the index page (`/`) and adding items to the cart (`/add_to_cart`). Implement functions to handle these routes.




@app.route('/')
def index():
    return render_template('index.html', products=products)    
    



 @app.route('/add_to_cart', methods=['POST'])
def add_to_cart():
    if request.method == 'POST':
        product_id = int(request.form['product_id'])
        product = next((p for p in products if p['id'] == product_id), None)
        if product:
            cart.append(product)
    return redirect(url_for('show_cart'))     
      



Dummy Data for Products and Cart:


Define dummy data for products and the shopping cart. These will be simple dictionaries representing products with their IDs, names, and prices.




# Dummy product data
products = [
    {"id": 1, "name": "Apple", "price": 10},
    {"id": 2, "name": "Orange", "price": 20},
    {"id": 3, "name": "Mango", "price": 30},
    {"id": 4, "name": "PineApple", "price": 40}
]      
      


 

Rendering Product Page:


In the `index` route, render the `index.html` template with the list of products passed as a variable.

 


Read also:

 


 

Handling Add to Cart Requests:


When a user clicks the "Add to Cart" button, a POST request is sent to the `/add_to_cart` route. In this route, retrieve the product ID from the form data, find the corresponding product from the products list, and add it to the cart list.

 

Rendering Cart Page:


Create a route (`/cart`) to render the `cart.html` template, passing the cart items as a variable.

 


app.py



from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# Dummy product data
products = [
    {"id": 1, "name": "Apple", "price": 10},
    {"id": 2, "name": "Orange", "price": 20},
    {"id": 3, "name": "Mango", "price": 30},
    {"id": 4, "name": "PineApple", "price": 40}
]

# Dummy shopping cart
cart = []


@app.route('/')
def index():
    return render_template('index.html', products=products)


@app.route('/add_to_cart', methods=['POST'])
def add_to_cart():
    if request.method == 'POST':
        product_id = int(request.form['product_id'])
        product = next((p for p in products if p['id'] == product_id), None)
        if product:
            cart.append(product)
    return redirect(url_for('show_cart'))


@app.route('/cart')
def show_cart():
    return render_template('cart.html', cart=cart)


if __name__ == '__main__':
    app.run(debug=True)




 

Testing:


Start the Flask development server and test the application by visiting the index page, adding products to the cart, and viewing the cart.

 

Conclusion:


Implementing the "Add to Cart" functionality in Python using Flask is a fundamental feature for any e-commerce website. With Flask's simplicity and flexibility, you can easily create robust web applications with user-friendly shopping experiences.



 

Previous Post Next Post