0

i crated add to cart funtionality for my website what problem i am facing right now is when a user logged in add something to cart and then got to the section od add to cart it load the page and show added items but when a user logged out and again signed in to the site and directly go add to cart page whitout adding any item it shows the above mentioned error i guess that every time it logged session got clear but i don't want it to happen any idea what causing the problem?

my views.py for cart

class Cart(View):
    def get (self, request): 
        ids = (list(request.session.get('cart').keys()))
        sections = Section.get_sections_by_id(ids)
        print(sections)
        return render(request, 'cart.html', {'sections': sections})
Shreyash mishra
  • 738
  • 1
  • 7
  • 30
  • 1
    when setting the ids , check for exceptions and handle them... looks like, Since there is no carts in the session , you cant use the keys() attribute on it... do something like when there are no carts in a session , create one .. – SANGEETH SUBRAMONIAM Jul 21 '21 at 05:49
  • Does this answer your question? [Persisting session variables across login](https://stackoverflow.com/questions/8256566/persisting-session-variables-across-login) – Abdul Aziz Barkat Jul 21 '21 at 06:10

1 Answers1

0

Yes it flushes the session during logout. You can check the source code here. To keep the session you can store the added product in persistent memory. May be you can store in database.

[docs]def logout(request):
    """
    Remove the authenticated user's ID from the request and flush their session
    data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if not getattr(user, 'is_authenticated', True):
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    # remember language choice saved to session
    language = request.session.get(LANGUAGE_SESSION_KEY)

    request.session.flush()

    if language is not None:
        request.session[LANGUAGE_SESSION_KEY] = language

    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

EDIT:

There can be multiple ways to do this :

1.) You can store it in cookies : Solution

2.) Overriding logout method with you custom logout : Solution

3.) Use database table to store the cart info.