Django Session Django.How

Author avatar wrote on 30/05/2022

Setting Up Sessions

In settings.py
To the MIDDLEWARE_CLASSES

‘django.contrib.sessions.middleware.SessionMiddleware’

And INSTALLED_APPS

‘django.contrib.sessions’

Set sussion value

request.session['customer_id'] = customer_id
request.session.modified = True

Remove sussion value

del request.session['customer_id']
request.session.modified = True

Check if in session

 if 'customer_id' in request.session:

Use and remove

if 'customer_id' in request.session:
customer = Customer.objects.get(id=request.session['customer_id'])
del request.session['customer_id']
request.session.modified = True

Access within a template

 {{ request.session.name }}

Pass session from view to another


def quote2(request, customer_id):
request.session['customer_id'] = customer_id
request.session.modified = True
return quote(request)
def quote(request):

And in urls

path('quote2/', views.quote3, name='quote3'),
path('quote', views.quote, name='quote'),

CRUDgen Django CRUD generator