Accessing a global variable using context processor in Django

Assuming I have a context processor:

def title(request): return {'titles': 'mytitle'} 

I can access this variable in the template as {{ titles }} .

But how can I do this in a view?

 def myview(request): print request.titles 

doesn't seem to work - 'WSGIRequest' object has no attribute 'titles'


Or maybe there is a better approach (than context processors) to have global variables available in both views and templates?

Thanks in advance.

+4
source share
3 answers

Context processors are by no means global variables. These are simply the functions that are triggered when the RequestContext is triggered, which add elements to this context. Therefore, they are available only where you have RequestContext, that is, in the template.

Your examples do not really give an idea of ​​which variables you want to get. If these are just some of the constants you want to use everywhere, a good way is to define them somewhere in the center, say in settings.py, and import this module where you need it - plus use a context processor to add them to the context .

+2
source

Add the context processor method path (folder.context_processor.application_context) to TEMPLATE_CONTEXT_PROCESSORS.

in my case application_context is the method that I defined inside the file context_processor.py and the method "application_context" returns {'titles': 'mytitle'}

if you want to use "title" as a global variable in views uses it this way

 global_var = RequestContext(request).get("app_config") titles = global_var.get("titles") print titles 

The only advantage is that the "same variable names" will be visible to the templates, as well as in your views "

+7
source

If you need data in your views, it’s cleaner to use Middleware in conjunction with the Context Processor:

  • Create a trivial user middleware to store some data of the request object, for example, request.x ( example ). Now you can access this in your views directly.
  • Include django.core.context_processors.request in TEMPLATE_CONTEXT_PROCESSORS to have request.x available from your templates.

See my related question: Django: how to provide context for all views (not templates)?

0
source

All Articles