Skip to content

Instantly share code, notes, and snippets.

@mbrochh
Created September 28, 2011 12:14
Show Gist options
  • Save mbrochh/1247790 to your computer and use it in GitHub Desktop.
Save mbrochh/1247790 to your computer and use it in GitHub Desktop.
Attach the django-shop cart to a User that started shopping anonymously
# add this soewhere where it gets loaded very early, i.e.
# your shop's models.py
from django.contrib.auth import login
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from registration.signals import user_activated
from shop.models.defaults.cart import Cart
@receiver(user_activated)
def login_user(sender, **kwargs):
user = kwargs.get('user')
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(kwargs.get('request'), user)
def attach_cart(sender, **kwargs):
user = kwargs.get('user')
user.backend = 'django.contrib.auth.backends.ModelBackend'
session = kwargs.get('request').session
cart_id = session.get('cart_id')
if cart_id:
# If the user logged in before, he left another cart bound to his user,
# we have to delete this old cart first.
cart = None
try:
old_cart = Cart.objects.get(user=user)
new_cart = Cart.objects.get(id=cart_id)
# If the new cart is empty and the old cart was not, we will keep
# the old cart.
if (new_cart.items.all().count() == 0
and old_cart.items.all().count() > 0):
new_cart.delete()
cart = old_cart
else:
old_cart.delete()
cart = new_cart
except Cart.DoesNotExist:
cart = Cart.objects.get(id=cart_id)
cart.user_id = user.id
cart.save()
if not user.is_authenticated():
login(kwargs.get('request'), user)
user_activated.connect(attach_cart)
user_logged_in.connect(attach_cart)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment