Template pitfalls

Debugging

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:

<pre>
{% debug %}
</pre>

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.

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:

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