added whole cart functionality

pull/2/head
KarolG 2023-05-25 03:16:01 +02:00
rodzic 3425875377
commit d41f4c2e12
6 zmienionych plików z 142 dodań i 55 usunięć

Wyświetl plik

@ -19,6 +19,6 @@
</li>
{% endfor %}
</ul>
<a href={% url 'cartPage' %} alt="Koszyk" > Cart </a>
<hr>
</div>

Wyświetl plik

@ -8,17 +8,18 @@ from wagtail import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
from search import views as search_views
from store.views import CartItemView, CartView
from store.views import CartItemView, CartView, CartPageView
urlpatterns = [
path("django-admin/", admin.site.urls),
path("admin/", include(wagtailadmin_urls)),
path("documents/", include(wagtaildocs_urls)),
path("search/", search_views.search, name="search"),
path('store/cart/', CartPageView.as_view(), name='cartPage'),
path('cart/', CartView.as_view(), name='cart'),
path('cart/item/<int:cart_item_id>/', CartItemView.as_view(), name='cart_item_remove'),
path('cart/item/', CartItemView.as_view(), name='add_to_cart'),
path('cart/item/<int:cart_item_id>/', CartItemView.as_view(),
name='cart_item_remove')
]

Wyświetl plik

@ -1,19 +1,10 @@
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!this.crossDomain) {
xhr.setRequestHeader('X-CSRFToken', $('input[name="csrfmiddlewaretoken"]').val());
}
}
});
$(document).on('click', '.add-to-cart-button', function(event) {
event.preventDefault();
const button = $(this);
const formData = new FormData();
const productID = $(this).data('product-id');
//const quantity = $(this).data('quantity');
const quantity = $('#quantity'+productID).val();
console.log(quantity)
const addToCartURL = $(this).data('add-to-cart-url');
const csrfToken = $(this).data('csrf-token');
formData.append('product_id', productID);
@ -28,8 +19,9 @@ $(document).on('click', '.add-to-cart-button', function(event) {
processData: false, // Prevent jQuery from processing the data
contentType: false, // Let the browser set the content type
success: function(data) {
alert(data.message);
button.prop('disabled', false);
// Show the options block
$('#add-to-cart-options').show();
button.prop('disabled', false);
},
error: function() {
button.prop('disabled', false);
@ -37,30 +29,97 @@ $(document).on('click', '.add-to-cart-button', function(event) {
});
});
$('#continue-shopping').on('click', function(event) {
event.preventDefault();
$('#add-to-cart-options').hide();
});
// Handle go to cart button click
$('#go-to-cart').on('click', function(event) {
event.preventDefault();
window.location.href = '/store/cart/';
});
const cartButton = document.getElementById('cart-button');
const cartDropdown = document.getElementById('cart-dropdown');
cartButton.addEventListener('click', function(event) {
event.preventDefault();
if (cartDropdown.style.display === 'none') {
cartDropdown.style.display = 'block';
fetchCartItems(); // Fetch and populate cart items
} else {
cartDropdown.style.display = 'none';
}
});
function fetchCartItems() {
fetch('/cart/')
.then(response => response.json())
.then(data => {
const cartItems = data.cart_items;
const cartItemsList = document.getElementById('cart-items');
cartItemsList.innerHTML = ''; // Clear existing cart items
cartItems.forEach(item => {
const li = document.createElement('li');
li.textContent = `Product ID: ${item.product_id}, Quantity: ${item.quantity}`;
cartItemsList.appendChild(li);
});
function fetchCartItems(xcsrf_token){
fetch('/cart/')
.then(response => response.json())
.then(data => {
const cartItems = data.cart_items;
const cartItemsList = document.getElementById('cart-items');
const csrf_token = xcsrf_token
cartItemsList.innerHTML = ''; // Clear existing cart items
cartItems.forEach(item => {
const li = document.createElement('li');
li.textContent = `Product ID: ${item.product_id}, Quantity: `;
const quantityInput = document.createElement('input');
quantityInput.type = 'number';
quantityInput.classList.add('quantity-input');
quantityInput.value = item.quantity;
quantityInput.min = '1';
quantityInput.step = '1';
quantityInput.dataset.productId = item.product_id;
quantityInput.dataset.csrfToken = csrf_token;
li.appendChild(quantityInput);
const removeButton = document.createElement('a');
removeButton.href = '#';
removeButton.classList.add('remove-from-cart-button');
removeButton.dataset.productId = item.product_id;
removeButton.dataset.csrfToken = csrf_token;
removeButton.textContent = 'Remove';
li.appendChild(removeButton);
cartItemsList.appendChild(li);
});
}
});
}
$(document).on('click', '.remove-from-cart-button', function(event) {
event.preventDefault();
const button = $(this);
const productId = button.data('product-id');
const csrfToken = button.data('csrf-token');
$.ajax({
type: 'DELETE',
url: '/cart/item/' + parseInt(productId) + '/',
headers: { 'X-CSRFToken': csrfToken },
dataType: 'json',
success: function(data) {
alert(data.message);
fetchCartItems(csrfToken);
},
error: function() {
alert("Error occurred while removing the item from the cart.");
}
});
});
$(document).on('change', '.quantity-input', function(event) {
event.preventDefault();
const input = $(this);
const formData = new FormData();
const productID = $(this).data('product-id');
const newQuantity = input.val();
const csrfToken = $(this).data('csrf-token');
formData.append('product_id', productID);
formData.append('quantity', newQuantity);
$.ajax({
type: 'POST',
url: '/../../cart/item/',
data: formData, // Use the serialized form data
headers: { 'X-CSRFToken': csrfToken },
dataType: 'json',
processData: false, // Prevent jQuery from processing the data
contentType: false, // Let the browser set the content type
});
});

Wyświetl plik

@ -1,8 +1,21 @@
{% extends "base.html" %}
{% block content %}
{% load static %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="{% static 'js/cart.js' %}"></script>
{% block content %}
<h1>Shopping Cart</h1>
<h2>Cart Items</h2>
<ul id="cart-items"></ul>
{% endblock %}
<div id="cart">
<ul id="cart-items">
{% for item in cart_items %}
<li>
Product ID: {{ item.product_id }},
Quantity:
<input type="number" class="quantity-input" value="{{ item.quantity }}" min="1" step="1" data-product-id="{{ item.product_id }}" data-csrf-token="{{ csrf_token }}">
<a href="#" class="remove-from-cart-button" data-product-id="{{ item.product_id }}" data-csrf-token="{{ csrf_token }}">Remove</a>
</li>
{% endfor %}
</ul>
</div>
{% endblock %}

Wyświetl plik

@ -4,16 +4,14 @@
{% block content %}
<div id="add-to-cart-options" style="display: none;">
<p>Item added to cart.</p>
<p>What would you like to do?</p>
<button id="continue-shopping">Continue Shopping</button>
<button id="go-to-cart">Go to Cart</button>
</div>
<div class="container mb-3">
<a href="#" class="btn btn-outline-success" id="cart-button">
<img src="{% static 'images/icons/cart.svg' %}" alt="Koszyk" />
</a>
<div id="cart-dropdown" style="display: none;">
<ul id="cart-items"></ul>
</div>
<div class="row row-cols-1 row-cols-md-3 g-4">
{% for item in items %}
<div class="col">

Wyświetl plik

@ -1,5 +1,7 @@
from django.http import JsonResponse
from django.views import View
from django.shortcuts import render
import json
class CartView(View):
@ -29,8 +31,22 @@ class CartItemView(View):
def delete(self, request, cart_item_id):
cart = request.session.get('cart', {})
if cart_item_id in cart:
del cart[cart_item_id]
if str(cart_item_id) in cart:
del cart[str(cart_item_id)]
request.session['cart'] = cart
return JsonResponse({'message': 'Item removed from cart.'})
return JsonResponse({'message': 'Item deleted from cart.'})
class CartPageView(View):
template_name = 'store/cart.html'
def get(self, request):
cart_view = CartView()
cart_response = cart_view.get(request)
cart_data = json.loads(cart_response.content)
context = {
'cart_items': cart_data['cart_items']
}
return render(request, self.template_name, context)