From 6c0ebc2b50927ede655d392f06b11cea470678a9 Mon Sep 17 00:00:00 2001 From: Raz Date: Sun, 23 Mar 2025 08:22:59 +0100 Subject: [PATCH] fix shop signup --- shop/cart.py | 18 ++++++++++++++++++ shop/signals.py | 16 ++++++++++++++++ tournaments/templates/registration/signup.html | 4 ---- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/shop/cart.py b/shop/cart.py index 76dcec6..18bb05c 100644 --- a/shop/cart.py +++ b/shop/cart.py @@ -74,3 +74,21 @@ def get_cart_item(request, item_id): return CartItem.objects.get(id=item_id, session_id=cart_id) except CartItem.DoesNotExist: raise Exception("Cart item not found") + +def transfer_cart(request, old_session_key): + """ + Transfer cart items from an anonymous session to an authenticated user's session + """ + from django.contrib.sessions.models import Session + from django.contrib.sessions.backends.db import SessionStore + + # Get the old session + try: + old_session = SessionStore(session_key=old_session_key) + # Check if there are cart items in the old session + if 'cart_items' in old_session: + # Transfer cart items to the new session + request.session['cart_items'] = old_session['cart_items'] + request.session.modified = True + except Session.DoesNotExist: + pass diff --git a/shop/signals.py b/shop/signals.py index 83be688..70ed58a 100644 --- a/shop/signals.py +++ b/shop/signals.py @@ -5,6 +5,8 @@ from django.conf import settings from django.urls import reverse from .models import Order, OrderItem, OrderStatus from django.db import transaction +from django.contrib.auth.signals import user_logged_in +from .cart import transfer_cart @receiver([post_save, post_delete], sender=Order) def send_order_notification(sender, instance, **kwargs): @@ -307,3 +309,17 @@ Merci de votre confiance. L'équipe PadelClub """ + +@receiver(user_logged_in) +def user_logged_in_handler(sender, request, user, **kwargs): + """ + When a user logs in, transfer any cart items from their anonymous session + """ + # Get the anonymous session key + if hasattr(request, 'session') and not request.session.is_empty(): + anonymous_session_key = request.session.session_key + + # After the user logs in, the session key changes + # So we transfer cart from the old session to the new session + if anonymous_session_key: + transfer_cart(request, anonymous_session_key) diff --git a/tournaments/templates/registration/signup.html b/tournaments/templates/registration/signup.html index a6a083f..d541d72 100644 --- a/tournaments/templates/registration/signup.html +++ b/tournaments/templates/registration/signup.html @@ -36,10 +36,6 @@ - - {% for message in messages %} -
{{ message }}
- {% endfor %}