Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving anonymous users the same functionality as registered ones

I'm working on an online store in Django (just a basic shopping cart right now), and I'm planning to add functionality for users to mark items as favorite (just like in stackoverflow). Models for the cart look something like this:

class Cart(models.Model):
    user = models.OneToOneField(User)

class CartItem(models.Model):
    cart = models.ForeignKey(Cart)
    product = models.ForeignKey(Product, verbose_name="produs")

The favorites model would be just a table with two rows: user and product.

The problem is that this would only work for registered users, as I need a user object. How can I also let unregistered users use these features, saving the data in cookies/sessions, and when and if they decides to register, moving the data to their user?

I guess one option would be some kind of generic relations, but I think that's a little to complicated. Maybe having an extra row after user that's a session object (I haven't really used sessions in django until now), and if the User is set to None, use that?

So basically, what I want to ask, is if you've had this problem before, how did you solve it, what would be the best approach?

like image 519
Adrian Mester Avatar asked May 29 '09 11:05

Adrian Mester


2 Answers

Seems to me that the easiest way to do this would be to store both the user id or the session id:

class Cart(models.Model):
    user = models.ForeignKey(User, null=True)
    session = models.CharField(max_length=32, null=True)

Then, when a user registers, you can take their request.session.session_key and update all rows with their new user id.

Better yet, you could define a "UserProxy" model:

class Cart(models.Model):
    user = models.ForeignKey(UserProxy)

class UserProxy(models.Model):
    user = models.ForeignKey(User, unique=True, null=True)
    session = models.CharField(max_length=32, null=True)

So then you just have to update the UserProxy table when they register, and nothing about the cart has to change.

like image 104
tghw Avatar answered Oct 03 '22 04:10

tghw


I haven't done this before but from reading your description I would simply create a user object when someone needs to do something that requires it. You then send the user a cookie which links to this user object, so if someone comes back (without clearing their cookies) they get the same skeleton user object.

This means that you can use your current code with minimal changes and when they want to migrate to a full registered user you can just populate the skeleton user object with their details.

If you wanted to keep your DB tidy-ish you could add a task that deletes all skeleton Users that haven't been used in say the last 30 days.

like image 45
Dave Webb Avatar answered Oct 03 '22 05:10

Dave Webb