views:

1190

answers:

2

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?

+1  A: 

You can filter out which views actually use context processors by only passing RequestContext(request) only to those which need it, e.g.:

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

# no context processors
return render_to_response('template.html', {'foo':'bar'})
tghw
I think that will work for this particular situation, but trying to think bigger here: what if I had 3 or 4 context processor functions that were needed by views at random, at that point should I just import them and call them in the views that need them? Because context processors are kind of an all-or-none thing right?
rennat
Right, the context processors in settings.py are all or none with RequestContext. A more flexible way to do it would be to subclass RequestContext for each set of processors you want and set the context processors there, so you could have SidebarContext and CommentsContext, etc. This would also get context processors out of settings.py, which would make them more app specific, which is better if you have many apps using context processors. So then, you'd just need a good way to chain them...
tghw
+7  A: 

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'})
Baldu
this seems like the better answer to me
Rasiel
Yea I switched it because the extra processors bit was what i was really after.
rennat