Ad

How To Set Globally-accessible Context Variables In Django Template Tags?

There is a template tag which returns a random element from the list. I also need to save all the elements that were in the list and the one that had been picked in context, and later depict that information in django-debug-toolbar panel.

from django import template
import random

register = template.Library()

@register.simple_tag(takes_context=True, name='pickrandomelementtag')
def pickrandomelementtag(context, list_of_random_elements):
    context.dicts[0]["key18"] = "value19"
    return random.choice(list_of_random_elements)

So I test setting the variables functionality with given line:

context.dicts[0]["key18"] = "value19" 

I am able to access the {{key18}} within the template, but my aim is set this variable in a manner that it would be accessible later on (globally?) from django-debug-toolbar panel. That's where i'm stuck.

Here is my django-debug-toolbar panels.py file:

from debug_toolbar.panels import Panel
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from django.template.response import SimpleTemplateResponse



class RandomPanel(Panel):
    name = "RandomPanel;"
    has_content = True
    template = 'panels/randompanel.html'

    def title(self):
        return _('Random Panel')

    def generate_stats(self, request, response):
        print('that is where I need to access key18')
        self.record_stats(
            {
                "request": request
            }
        )

How would I access context variable key18 in generate_stats method of RandomPanel class object? Or maybe context is a wrong place to set custom cariables within template tags and you'd advise other approaches? Many thanks!

Ad

Answer

You can actually store the information in the request itself. Assuming that the context_processor has django.template.context_processors.request (which is there in default settings)

@register.simple_tag(takes_context=True, name='pickrandomelementtag')
def pickrandomelementtag(context, list_of_random_elements):
    context['request'].META['MY_INFO'] = "value19"
    return random.choice(list_of_random_elements)

Then you have the request object in the Panel where you can use this information.

Ad
source: stackoverflow.com
Ad