Monday, 29 July 2019

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 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!



from How to set globally-accessible context variables in django template tags?

No comments:

Post a Comment