Django Getting RequestContext in custom tag

Posted by greggory.hz on Stack Overflow See other posts from Stack Overflow or by greggory.hz
Published on 2011-01-02T02:37:18Z Indexed on 2011/01/02 8:54 UTC
Read the original article Hit count: 208

Filed under:
|
|

I'm trying to create a custom tag. Inside this custom tag, I want to be able to have some logic that checks if the user is logged in, and then have the tag rendered accordingly. This is what I have:

class UserActionNode(template.Node):
    def __init__(self):
        pass

    def render(self, context):
        if context.user.is_authenticated():
            return render_to_string('layout_elements/sign_in_register.html');
        else:
            return render_to_string('layout_elements/logout_settings.html');

def user_actions(parser, test):
    return UserActionNode()

register.tag('user_actions', user_actions)

When I run this, I get this error:

Caught AttributeError while rendering: 'Context' object has no attribute 'user'

The view that renders this looks like this:

return render_to_response('start/home.html', {}, context_instance=RequestContext(request))

Why doesn't the tag get a RequestContext object instead of the Context object? How can I get the tag to receive the RequestContext instead of the Context?

EDIT:

Whether or not it's possible to get a RequestContext inside a custom tag, I'd still be interested to know the "correct" or best way to determine a user's authentication state from within the custom tag. If that's not possible, then perhaps that kind of logic belongs elsewhere? Where?

© Stack Overflow or respective owner

Related posts about python

Related posts about django