I'm recently experimenting with session variables instead of writing everything in base. I'm building an app for counter sales (cart, user, customer session variables). After the order and its items are saved in DB, I want to save the customer and clear its related session variablesin request.session['customers'] dict list.
def save_customer(request, store):
# save only customers != Client Magasin
customers = request.session['customers'].copy()
print(customers)
current_customer = list(filter(
lambda i: i['user'] == request.user.pk and i['store'] == store, customers))[0]
id = current_customer.pop('id')
nom = current_customer['nom']
if nom != 'Client Magasin':
current_customer.pop('store')
current_customer.pop('user')
customer = Customer.objects.create(**current_customer)
# return Customer for adding it to order
return customer
else:
# return Client Magasin
return Customer.objects.get(pk=1)
When I print out request.session['customers'] I can see ID, STORE and USER keys. But after the lambda, those keys are removed from the original request.session['customers']
I know that because further in my code, I wan't to filter again this list
def remove_same_customer(request):
customers_list = request.session['customers'].copy()
print(customers_list)
# new_customers = list(filter(
# lambda i: i['store'] != request.session['cart_warehouse'] and i['user'] !=
request.user, customers_list))
# request.session['customers'] = new_customers
# request.session.modified = True
I have commented the 4 last lines because they trigger an error because ID, STORE and USER keys can't be found. This is confirmed by using print(customers_list)
what am I doing wrong ? PS : dunno if dict.copy() is useful in my case but I tried this after the error raised.