views:

125

answers:

3

Say I'm writing a Django app, and all the templates in the app require a certain variable.

The "classic" way to deal with this, afaik, is to write a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in the settings.py.

My question is, is this the right way to do it, considering that apps are supposed to be "independent" from the actual project using them?

In other words, when deploying that app to a new project, is there any way to avoid the project having to explicitly mess around with its settings?

A: 

Yeah, adding a context processor is the most recommended approach to achieve this.

phoenix24
+1  A: 

Context processors are very useful and I wouldn't be too shy in using them, but in some situations it doesn't make sense.

This is a technique I use when I need to include something simple to all views in an app. I cannot attest that this is the 'proper' way to do things, but it works for our team:

I'll declare a global dictionary template_vars at the top of the file. Every view would add its own variables to this dictionary and pass it to the template, and it returns template_vars in the render_to_response shortcut.

It looks something like this:

template_vars = {
    'spam': 'eggs',
    }

def gallery(request):
    """
    portfolio gallery
    """

    template_vars['projects'] = Projects.objects.all()
    return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))
digitaldreamer
+1  A: 

Your assumption that apps can just be added in a project without touching the project's settings is not correct.

If you add an application to a project, you have to edit the settings, since you must add it in the INSTALLED_APPS tuple.

So why not edit the context processor list?

Olivier
Yep. If your trepidation is that you don't want to pass that extra burden on to apps, then I say don't worry about it. I'm already used to the notion of modifying my INSTALLED_APPS and CONTEXT_PROCESSORS settings as apps require.
Koobz
Are those the only two things that need editing? Because a while ago, I realized the you have to make sure your static_media folder contains the app's static media. In other words, we're talking about 3 different "actions" you have to remember to take when moving the app. I guess I'm just trying to get "more" out of apps than they're meant for.
Edan Maor
Middleware is another common additional setting for apps. In the grand scheme of things editing a handful of lines in urls and settings is minor in terms of the functional gains you get from modular apps.
digitaldreamer