David542
David542

Reputation: 110173

Storing session variables

I have four session variables--

location = request.session['location']
computer = request.session['computer']
phone = request.session['phone']
hobby = request.session['hobby']

I have several view functions that need to use these variables. Is there a way I can store these variables in a separate function and call them from the other functions? If so, how would I do that? Thank you.

Upvotes: 1

Views: 6011

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

Not sure I understand? You can call session variables from wherever the request is available i.e. your views

def some_view(request):
    var1 = request.session.get('location', False)
    if var1:
        # do something
    else:
        # do something else

see more here: https://docs.djangoproject.com/en/dev/topics/http/sessions/#examples


From your comment:

getting_started_step_one(request)

This function is being passed request as a parameter, and therefore has access to all of request's variables. One of these variables/objects is session, and this session object in turn has access to the variables you are looking for (username, location etc..). So all you have to do is:

def getting_started_step_one(request):
    location = request.session.get("location", False)

Upvotes: 4

Related Questions