0

I am trying to build a session in django like so but the following does not lead to an updated session

def index(request):
  if not request.user.is_authenticated:
    return render(request, "login.html", {"message": None})
  if 'foo' not in request.session:
    request.session["foo"] = {}
  if request.method == 'POST':
    form = NewLineItemForm(request.POST)
    if form.is_valid():
      item = Item.objects.create(name=name)
      request.session["foo"][item.id] = item.name
  context = {
    "foo": request.session['foo'],
    "form": NewLineItemForm()
  }
  
  return render(request, "index.html", context)

However, when I add the following to another key on the session does the entire thing, including the original key (foo) update:

def index(request):
  if not request.user.is_authenticated:
    return render(request, "login.html", {"message": None})
  if 'foo' not in request.session:
    request.session["foo"] = {}
  if 'task' not in request.session:
    request.session['task'] = []
  if request.method == 'POST':
    form = NewLineItemForm(request.POST)
    if form.is_valid():
      item = Item.objects.create(name=name)
      request.session["foo"][item.id] = item.name
      request.session["task"] += ['baz']
  context = {
    "foo": request.session['foo'],
    "form": NewLineItemForm()
  }
  
  return render(request, "index.html", context)

I was wondering how I can keep what's intended in the first block without having to rely on the changes in the second block. Thank you.

reactor
  • 1,722
  • 1
  • 14
  • 34
  • 1
    As explained in the docs linked in the top answer of the dupe, Django sessions are saved only if the dictionary values have been assigned or deleted. In your case you are altering the the dict at `request.session["foo"]` so you need to explicitly set the `modified` attribute. Your addition of a new key was achieving this in a roundabout way – shriakhilc Oct 22 '22 at 18:07

0 Answers0