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!
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.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module