Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it appropriate to use Django context processors?

If about half of my views require the same data set, is it appropriate to use a context processor to make the data always available, or is there a better way to avoid repeating the code to get that data across several views without querying the data if it won't be used in the view?

like image 666
rennat Avatar asked May 06 '09 19:05

rennat


People also ask

What is the use of context processors in Django?

A context processor is a Python function that takes the request object as an argument and returns a dictionary that gets added to the request context. They come in handy when you need to make something available globally to all templates.

What is RequestContext Django?

Context, but Django also comes with a subclass, django. template. RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default – things like the HttpRequest object or information about the currently logged-in user.

How do you solve template does not exist in Django?

Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.


1 Answers

The RequestContext initializer will run any context processors listed in the settings file, but it also takes a list of additional processors to run. Any general purpose context processors can be put in settings.py and more specific ones can be added to the RequestContext on a case-by-case basis.

Leave RequestContext out altogether to not run any context processors.

# want context processors listed in settings.py as well as some more specific ones
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request, processors = extra_processors))

# want only context processors listed in settings.py
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request))

# no context processors
return render_to_response('template.html', {'foo':'bar'})
like image 73
Baldu Avatar answered Oct 26 '22 11:10

Baldu