Hanpan
Hanpan

Reputation: 10261

Template tag and request object

Each time a request is made to my app, I am using middleware to retrieve and store a 'Page' object which has information relevant that particular page. I am storing a reference to this object in the request object, here is an example:

class PageMiddleware(object):
    def process_request(self, request):
        if not hasattr(request, 'page'):
            request.page = Page.objects.get(slug=<slug>)
        return None

It works well enough, but I want to access this object in a template tag. Template tags only have a reference to 'context' thought, meaning I am unable to see my Page object.

I know I can use a custom context processor for this but that means modifying the settings file further and I'd like to try and keep this app as encapsulated as possible. I noticed, for example, that the Debug Toolbar app manages to append data to the template context without modifying the TEMPLATE_CONTEXT_PROCESSORS.

In short, I want to access my Page object in a template tag ideally by just using middleware. Any ideas?

Edit: I am using a standard template tag, with the following class:

class GetPageContentNode(Node):
    def __init__(self, key):
        self.key = key

    def render(self, context):
        return context['request'].page

Upvotes: 1

Views: 6907

Answers (3)

santiagobasulto
santiagobasulto

Reputation: 11726

Try this:

class GetPageContentNode(Node):
    def __init__(self, key):
        self.key = key

    def render(self, context):
        request = template.Variable('request').resolve(context) # here's the magic!
        return request.page

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77399

Call every render_to_response with a context_instance parameter, like:

def some_view(request):
    # ...
     return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

EDITED as sugested by Daniel Roseman:

And add django.core.context_processors.request to your TEMPLATE_CONTEXT_PROCESSORS settings.

Upvotes: 1

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

Have a look at this, you can get access to the request object (and your object) by passing takes_context when registering the template tag

Access request in django custom template tags

Have a search for "takes_context" on this page:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-the-tag

Upvotes: 2

Related Questions