julianwachholz / django-guest-user

A Django app that allows visitors to interact with your site as a guest user without requiring registration.
https://django-guest-user.readthedocs.io/
MIT License
74 stars 12 forks source link

How to log in instead of registering a new user? #3

Closed dylanjcastillo closed 2 years ago

dylanjcastillo commented 2 years ago

Hi @julianwachholz,

Thanks a lot for working on this package, it's very useful!

I had a question I hoped you could help me answer: Is there a way to allow the user to log in, instead of creating a new user during the conversion? So that if a user hadn't logged in before putting items in the cart, he can still keep them

Thank you.

Best, Dylan

julianwachholz commented 2 years ago

Hi Dylan, thank you for your interest and patience!

This can be a little tricky to support, since every project's related models are different. One approach I can think of is writing your own login view which will transfer the Guest user's associated objects to the newly logged in one, e.g.:

from django.contrib.auth.views import LoginView as BaseLoginView

class LoginView(BaseLoginView):
  def form_valid(self, form):
    guest = None
    if is_guest_user(request.user):
      guest = request.user
    user = form.get_user()

    # Transfer current cart object for example
    user.cart = guest.cart
    user.save()
    guest.delete()

    return super().form_valid(form)
dylanjcastillo commented 2 years ago

Thank you! I ended up using a different approach, but will use this next time