Search code examples
djangodjango-viewsdjango-sessions

Create and Retrive django session objects


I have customised the django default user table and used it for user signup and login. Now I need to create django session object to create a shopping cart (like that of an ecommerce website) which is user specific.How to create and retrive session objects in django??


Solution

  • Django provides full and built-in support for sessions (also anonymous sessions). First thing you need to enable the middleware session in the settings. Then you can easily retrieve the session as a dict in the views calling the request param at any point in your view.

    def my_view(request):
        # Get a param:
        my_param = request.session.get('my_param'):
        # Set a param:
        request.session['my_param'] = True
        # Some logic here ...
        return HttpResponse('...')
    

    Have a look at the docs here