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

Wyświetl plik

@ -1,35 +1,66 @@
// Add item to cart on form submission $.ajaxSetup({
$('#add-to-cart-form').on('submit', function(event) { 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(); event.preventDefault();
const form = $(this); const button = $(this);
const formData = new FormData(form[0]); // Serialize the form data correctly 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({ $.ajax({
type: form.attr('method'), type: 'POST',
url: form.attr('action'), url: addToCartURL,
data: formData, // Use the serialized form data data: formData, // Use the serialized form data
headers: { 'X-CSRFToken': csrfToken },
dataType: 'json', dataType: 'json',
processData: false, // Prevent jQuery from processing the data processData: false, // Prevent jQuery from processing the data
contentType: false, // Let the browser set the content type contentType: false, // Let the browser set the content type
success: function(data) { success: function(data) {
alert(data.message); 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 cartButton.addEventListener('click', function(event) {
function fetchCartItems() { event.preventDefault();
fetch('/cart/') if (cartDropdown.style.display === 'none') {
.then(response => response.json()) cartDropdown.style.display = 'block';
.then(data => { 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 cartItems = data.cart_items;
const cartItemsList = $('#cart-items'); const cartItemsList = document.getElementById('cart-items');
cartItemsList.empty(); cartItemsList.innerHTML = ''; // Clear existing cart items
cartItems.forEach(item => { cartItems.forEach(item => {
const li = $('<li>').text(`Product ID: ${item.product_id}, Quantity: ${item.quantity}`); const li = document.createElement('li');
cartItemsList.append(li); li.textContent = `Product ID: ${item.product_id}, Quantity: ${item.quantity}`;
cartItemsList.appendChild(li);
}); });
}); });
} }

Wyświetl plik

@ -1,16 +1,24 @@
{% load static %} {% 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-header">{{item.title}}</div>
<div class="card-body"> <div class="card-body">
<img src="{{item.main_image.url}}" class="rounded mx-auto d-block" style="width: 10rem; height: 10 rem;"> <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> <p class="card-text">{{item.description}}</p>
<div class="text-end"> <div class="text-end">
<a href="#" class="btn btn-outline-primary">Details</a> <a href="#" class="btn btn-outline-primary">Details</a>
<a href="#" class="btn btn-outline-success"> <div class="quantity-input">
<img src = "{% static 'images/icons/cart.svg' %}" alt="Koszyk"/> <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> </a>
</div> </div>
</div> </div>

Wyświetl plik

@ -1,9 +1,19 @@
{% extends 'base.html'%} {% extends 'base.html'%}
{% load static %}
<script src="{% static 'js/cart.js' %}"></script>
{% block content %} {% block content %}
<div class="container mb-3"> <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"> <div class="row row-cols-1 row-cols-md-3 g-4">
{% for item in items %} {% for item in items %}
<div class="col"> <div class="col">

Wyświetl plik

@ -19,7 +19,6 @@ class CartItemView(View):
allowed_methods = ['POST', 'DELETE'] allowed_methods = ['POST', 'DELETE']
def post(self, request): def post(self, request):
try:
product_id = request.POST.get('product_id') product_id = request.POST.get('product_id')
quantity = request.POST.get('quantity') quantity = request.POST.get('quantity')
cart = request.session.get('cart', {}) cart = request.session.get('cart', {})
@ -27,8 +26,6 @@ class CartItemView(View):
request.session['cart'] = cart request.session['cart'] = cart
return JsonResponse({'message': 'Item added to 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): def delete(self, request, cart_item_id):
cart = request.session.get('cart', {}) cart = request.session.get('cart', {})