Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated cart functionality. #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions products/templates/cart.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{% extends 'base.html' %}

{% block content %}
<div class="container mt-5">
<h1>Your Cart</h1>
{% if cart_items %}
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for item in cart_items %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.product.price }}</td>
<td>${{ item.total_price }}</td>
<td>
<a href="#" class="btn btn-danger btn-sm">Remove</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h3>Total: ${{ total_amount }}</h3>
<a href="#" class="btn btn-success">Proceed to Checkout</a>
{% else %}
<p>Your cart is empty.</p>
{% endif %}
</div>
{% endblock %}
74 changes: 52 additions & 22 deletions products/templates/index.html
Original file line number Diff line number Diff line change
@@ -1,28 +1,58 @@
{% extends 'base.html' %}

{% block content %}
<div class="jumbotron jumbotron-fluid text-center">
<div class="container">
<h1 class="display-4">All Products</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
</div>
</div>
<div class="jumbotron jumbotron-fluid text-center">
<div class="container">
<h1 class="display-4">All Products</h1>
<p class="lead">This is a modified jumbotron that occupies the entire horizontal space of its parent.</p>
</div>
</div>

<div class="container">
<div class="row">
{% for product in products %}
<div class="col-md-3" style="margin-bottom: 10px; padding: 0px 5px;">
<div class="card" style="">
<div style="background: #020202 url({{ product.image_url }}); background-size: cover; background-position: center; background-repeat: no-repeat; width: 100%; height: 250px;"></div>
<div class="card-body">
<h5 class="card-title">{{ product.name }} - <strong>${{ product.price }}</strong></h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the
card's content.</p>
<a href="#" class="btn btn-primary">Add to cart</a>
</div>
</div>
<div class="container">
<div class="row">
{% for product in products %}
<div class="col-md-3" style="margin-bottom: 10px; padding: 0px 5px;">
<div class="card">
<div
style="background: #020202 url({{ product.image_url }}); background-size: cover; background-position: center; background-repeat: no-repeat; width: 100%; height: 250px;">
</div>
{% endfor %}
<div class="card-body">
<h5 class="card-title">{{ product.name }} - <strong>${{ product.price }}</strong></h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the
card's content.</p>
<button class="btn btn-primary add-to-cart" data-id="{{ product.id }}">Add to cart</button>
</div>
</div>
</div>
</div>
{% endblock %}
{% endfor %}
</div>
</div>

<script>
document.querySelectorAll('.add-to-cart').forEach(button => {
button.addEventListener('click', function () {
const productId = this.getAttribute('data-id');

fetch(`/products/add-to-cart/${productId}/`, { // Fixed URL formatting
method: 'GET',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Product added to cart successfully!');
} else {
alert('Failed to add product to cart.');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred.');
});
});
});
</script>

{% endblock %}
11 changes: 6 additions & 5 deletions products/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from django.urls import path
from . import views

from .views import index, new, add_to_cart, cart

urlpatterns = [
path('', views.index),
path('new/', views.new)
]
path('', index, name='index'),
path('new/', new, name='new'),
path('add-to-cart/<int:product_id>/', add_to_cart, name='add-to-cart'),
path('cart/', cart, name='cart'),
]
38 changes: 38 additions & 0 deletions products/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from .models import Product
from django.shortcuts import redirect
from .models import Product


# Create your views here.
Expand All @@ -14,3 +17,38 @@ def index(request):
def new(request):
return HttpResponse('Welcome to PyShop New Arrivals')

# views.py


def add_to_cart(request, product_id):
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
cart = request.session.get('cart', {})
cart[product_id] = cart.get(product_id, 0) + 1 # Increment quantity
request.session['cart'] = cart
return JsonResponse({'success': True, 'message': 'Product added to cart'})
else:
return redirect('index') # Redirect to index if not an AJAX request


def cart(request):
cart = request.session.get('cart', {})
cart_items = []

for product_id, quantity in cart.items():
try:
product = Product.objects.get(id=product_id)
cart_items.append({
'product': product,
'quantity': quantity,
'total_price': product.price * quantity
})
except Product.DoesNotExist:
pass

# Calculate the total amount for the cart
total_amount = sum(item['total_price'] for item in cart_items)

return render(request, 'cart.html', {
'cart_items': cart_items,
'total_amount': total_amount
})
37 changes: 37 additions & 0 deletions templates/Cart.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{% extends 'base.html' %}

{% block content %}
<div class="container mt-5">
<h1>Your Cart</h1>
{% if cart_items %}
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for item in cart_items %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>${{ item.product.price }}</td>
<td>${{ item.total_price }}</td>
<td>
<a href="#" class="btn btn-danger btn-sm">Remove</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h3>Total: ${{ total_amount }}</h3>
<a href="#" class="btn btn-success">Proceed to Checkout</a>
{% else %}
<p>Your cart is empty.</p>
{% endif %}
</div>
{% endblock %}
7 changes: 4 additions & 3 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
<li class="nav-item">
<a class="nav-link" href="/products/new">New Arrivals</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'cart' %}">Cart ({{ request.session.cart|length|default:0 }})</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
Expand All @@ -38,7 +41,6 @@

<main>
{% block content %}

{% endblock %}
</main>

Expand All @@ -48,7 +50,6 @@
<a href="#">Back to top</a>
</p>
<p>PyShop is a © of <strong><a href="https://github.com/thisishaykins/">Thisishaykins</a></strong>, but please download and customize it for yourself!</p>
<!-- <p>New to Bootstrap? <a href="https://getbootstrap.com/">Visit the homepage</a> or read our <a href="/docs/4.3/getting-started/introduction/">getting started guide</a>.</p>-->
</div>
</footer>
<!-- Optional JavaScript -->
Expand All @@ -57,4 +58,4 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</html>