[Django]-Django TEMPLATE_CONTEXT_PROCESSORS are being called too many times

3👍

Setting function in TEMPLATE_CONTEXT_PROCESSORS have the advantage to use it in all pages. But be aware that even if you did not call it or use it, still it loads the queries because it directly call from the settings. It will result to bad performance. Use only the context processor when you have to use it almost in every template like the user or other parameters that don’t have a lot of cost.

5👍

The context processors are called one by one when a RequestContext instance is initialized, thus you may have multiple RequestContext instances being initialized. Could you debug to find out them, for example by using a RequestContext subclass to print when it’s __init__ is being called?

Or you could return a lazy object which delays its evaluation until really needed, and see whether the count of the duplicated queries drops:

def numeros(request):
    return {'a': table1.objects.count,
            'b': table2.objects.count,
            ...}
👤okm

0👍

I had more or less the same problem. So went into one of the functions that was called by the RequestContext (from TEMPLATE_CONTEXT_PROCESSORS) and logged the traceback, to see where the response was trickered:

import traceback

logger.info(traceback.format_list(traceback.extract_stack()))

You could also print it if you have no logger activated.

In my case it was because I had debug_toolbar on, which also called RequestContext.

Leave a comment