Peter Tirrell
Peter Tirrell

Reputation: 3003

How to access session variable in Mako template and Pyramid?

I have this Pyramid view:

def ClientView(request):
    session = request.session
    session['selectedclientid'] = 'test' #selectedclient.id
    session.save()
    return dict(
        logged_in=authenticated_userid(request)
    )

And then in my template I'm just trying something like this:

% if session['selectedclientid'] != None:
                The session has something
            % endif

And this gives me a template error:

    % if session['selectedclientid'] != None:
TypeError: 'Undefined' object has no attribute '__getitem__'

Am I setting the session variable wrong? Am I querying it wrong? Do I even need to make a copy of the request.session object and .save() it in the first place? Couldn't I just do request.session['myvariable'] = 'foo' and set it that way? That still doesn't help me in pulling it back in the template.

Upvotes: 1

Views: 1927

Answers (2)

Michael Merickel
Michael Merickel

Reputation: 23331

request.session is the variable in your template. Not session. This is why you are getting the Undefined exception.

Upvotes: 2

Peter Tirrell
Peter Tirrell

Reputation: 3003

I think I got it. I can still set it like so:

request.session['selectedclientid'] = 'test'

But reading it back worked like this:

% if 'selectedclientid' in request.session:
                The session has something ${request.session['selectedclientid']}
            % endif

Upvotes: 0

Related Questions