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.