few fixes, users can add products to cart from listing page

pull/2/head
KarolG 2023-05-23 06:01:00 +02:00
rodzic 7e7f9ee4b3
commit 3425875377
5 zmienionych plików z 76 dodań i 33 usunięć

Wyświetl plik

@ -1,7 +1,6 @@
from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from django.views.generic import TemplateView
from wagtail.admin import urls as wagtailadmin_urls
@ -19,9 +18,7 @@ urlpatterns = [
path('cart/', CartView.as_view(), name='cart'),
path('cart/item/', CartItemView.as_view(), name='add_to_cart'),
path('cart/item/<int:cart_item_id>/', CartItemView.as_view(),
name='cart_item_remove'),
path('', TemplateView.as_view(template_name='index.html'), name='index'),
name='cart_item_remove')
]

Wyświetl plik

@ -1,35 +1,66 @@
// Add item to cart on form submission
$('#add-to-cart-form').on('submit', function(event) {
$.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 form = $(this);
const formData = new FormData(form[0]); // Serialize the form data correctly
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);
formData.append('quantity', quantity); // Serialize the form data correctly
button.prop('disabled', true);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
type: 'POST',
url: addToCartURL,
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
success: function(data) {
alert(data.message);
fetchCartItems();
button.prop('disabled', false);
},
error: function() {
button.prop('disabled', false);
}
});
});
});
const cartButton = document.getElementById('cart-button');
const cartDropdown = document.getElementById('cart-dropdown');
// Fetch cart items and update the display
function fetchCartItems() {
fetch('/cart/')
.then(response => response.json())
.then(data => {
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 = $('#cart-items');
cartItemsList.empty();
const cartItemsList = document.getElementById('cart-items');
cartItemsList.innerHTML = ''; // Clear existing cart items
cartItems.forEach(item => {
const li = $('<li>').text(`Product ID: ${item.product_id}, Quantity: ${item.quantity}`);
cartItemsList.append(li);
const li = document.createElement('li');
li.textContent = `Product ID: ${item.product_id}, Quantity: ${item.quantity}`;
cartItemsList.appendChild(li);
});
});
}
});
}

Wyświetl plik

@ -1,16 +1,24 @@
{% load static %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="{% static 'js/cart.js' %}"></script>
<div class="card h-100" style="width: 15rem;">
<div class="card h-100" style="width: 15rem;">
<div class="card-header">{{item.title}}</div>
<div class="card-body">
<img src="{{item.main_image.url}}" class="rounded mx-auto d-block" style="width: 10rem; height: 10 rem;">
<p class="card-text">{{item.description}}</p>
<div class="text-end">
<a href="#" class="btn btn-outline-primary">Details</a>
<a href="#" class="btn btn-outline-success">
<img src = "{% static 'images/icons/cart.svg' %}" alt="Koszyk"/>
<div class="quantity-input">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity{{item.id}}" name="quantity" min="1" value="1">
</div>
<a href="#" class="btn btn-outline-success add-to-cart-button"
data-product-id="{{ item.id }}"
data-add-to-cart-url="{% url 'add_to_cart' %}"
data-csrf-token="{{ csrf_token }}">
<img src="{% static 'images/icons/cart.svg' %}" alt="Koszyk"/>
</a>
</div>
</div>

Wyświetl plik

@ -1,9 +1,19 @@
{% extends 'base.html'%}
{% load static %}
<script src="{% static 'js/cart.js' %}"></script>
{% block content %}
<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

@ -19,7 +19,6 @@ class CartItemView(View):
allowed_methods = ['POST', 'DELETE']
def post(self, request):
try:
product_id = request.POST.get('product_id')
quantity = request.POST.get('quantity')
cart = request.session.get('cart', {})
@ -27,8 +26,6 @@ class CartItemView(View):
request.session['cart'] = cart
return JsonResponse({'message': 'Item added to cart.'})
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
def delete(self, request, cart_item_id):
cart = request.session.get('cart', {})