Search code examples
djangosession-variables

Django filtering in views.py with a session variable


I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py.

def allcontexts(request):
    allcontexts = Context.objects.all()
    return render(request, 'context_manager/context_manager.html',
    {
    'allcontexts':allcontexts,
    })

In order to filter I change the second row to the following

    allcontexts = Context.objects.filter(context_number=____)

In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable]

I can't seem to figure out the correct syntax, any ideas?


Solution

  • You can access session variables using request.session.get() syntax:

    allcontexts = Context.objects.filter(context_number=request.session.get("context_number"))