[ACCEPTED]-Django - accessing the RequestContext from within a custom filter-django-templates

Accepted answer
Score: 12

If you create a template tag instead of 2 a filter, you are given the context to work 1 with (which contains the request). http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags

Score: 7

I would have to agree with Adam that migrating 12 the code to a custom tag is the best way.

However, a 11 client needed to record the use of certain 10 filters only when a page was published and 9 had a HUGE inventory of templates that used 8 the existing filter syntax. It would have 7 been a costly undertaking to rewrite all 6 the templates. So, I came up with this 5 simple function that extracts the context 4 from the call stack:

https://gist.github.com/drhoden/e05292e52fd5fc92cc3b

def get_context(max_depth=4):
    import inspect
    stack = inspect.stack()[2:max_depth]
    context = {}
    for frame_info in stack:
        frame = frame_info[0]
        arg_info = inspect.getargvalues(frame)
        if 'context' in arg_info.locals:
            context = arg_info.locals['context']
            break
    return context

Be sure to read my warnings, but 3 this DOES give standard filters access to 2 the context (when it is available) WITHOUT 1 having to turn your filter into a tag.

Score: 5

This can be done using a filter. First make 7 sure that you have "django.core.context_processors.request" in you TEMPLATE_CONTEXT_PROCESSORS. If you don't, you 6 can add this to your settings.py file:

TEMPLATE_CONTEXT_PROCESSORS += (
    "django.core.context_processors.request"
)

Then 5 in your template, your filter will look 4 like this (assuming your session variable 3 is named 'currency_type'):

{{value|currency:request.session.currency_type}}

Or is something 2 like this what you are considering fairly 1 horrible?

Score: 0

A somehow less hacky solution to Daniel 5 Rhoden's proposal is, to use threading.local(). Define a 4 middleware class, which stores your request as 3 a global object inside your local thread, and 2 add that class to your MIDDLEWARE_CLASSES.

Now a template filter 1 can easily access that request object.

More Related questions