Template pitfalls

Here's how to dodge some of the more obvious template pitfalls:


Not a pitfall, but a tip:

Use {% debug %} in a template block if you want to know what is defined and can be used in a template.

The debug output is pretty ugly unless you look at it through View Source, or you can do it this way:

{% filter linebreaks %}
  {% debug %}
{% endfilter %}

or more simply:

  {% debug %}

custom context variables for generic views

More advanced versions of the base template (mine is base.html, following the model set in the administration interface) might need a consistent set of context variables generated on the fly based on the identity of the current user, what they're doing, what's happening elsewhere on the site, and so on.

If you're using generic views, though, there's no obvious way to make these context variables available.

The solution is to use custom template tags, which can modify a page's context variables on the fly.

If your needs are middling simple, or you don't want to have to write your own custom template tag from scratch, I've developed a generic option: vars, which defines a fairly generic pushvars tag that calls the function of your choice and pushes its results into the current context.

I'm posting this to atone for my previous crummy advice on this Wiki page. - garthk

The problem with the above is that 'the function of your choice' might need to take the HttpRequest object as an argument, which isn't currently possible. An alternative solution is to call the generic views manually, rather than automatically via the URL dispatcher. With this method, you set URL dispatcher to call your custom view function, which simply sets gets any required extra context variables, using the request object, then calls the relevant generic view function. For example:

from django.views.generic import list_detail

def index(request):
 return list_detail.object_list(request, 'your_app_name', 'model_module_name', 
  extra_context = do_something_with_request(request),
  template_name = 'your_template_name',

This also has the advantage that every argument to object_list() can be dynamic and depend on the request, e.g. paginate_by could be a user preference or a query string parameter. I'm not sure if this is a perfect solution, but it's pretty easy. - luke plant

Last modified 19 years ago Last modified on Sep 16, 2005, 12:38:37 PM
Note: See TracWiki for help on using the wiki.
Back to Top