Home > OS >  Django session variables not saving when back button clicked
Django session variables not saving when back button clicked

Time:12-24

On my page i am trying to implement a recently viewed section on my home page. The problem is when I append a new item to request.session["recently-viewed"], the item i just viewed gets deleted from the list when i load a new page.

The item view is a page which displays the details about a specific item. I want that particular item to be added and saved into a session variable. When the user visits any other page the session variable "recently-viewed" should be saved. Recently viewed items can then be displayed on the home page.

There is a similar question that has been asked but the only answer was a solution using javascript. If possible could solutions stay away from javascript.

views.py

def item(request, item_id):
    if "recently-viewed" not in request.session:
        request.session["recently-viewed"] = [item_id]
    else:
        request.session["recently-viewed"].append(item_id)

when in item view:

request.session["recently-viewed"] = ["item1", "item2"]

when another page is loaded:

request.session["recently-viewed"] = ["item1"]

CodePudding user response:

Django, by default, only saves the session when a key has been deleted or assigned to. Because you are mutating a list you need to tell Django to save the session

request.session["recently-viewed"].append(item_id)
request.session.modified = True
  • Related