pprinting the Django context object

This was non-obvious to me for quite some time, and I tried several different approaches before settling on this one:

If you would like to pprint your Django Context (or RequestContext) object from within a template itself, there are several approaches you can take.  The easiest way I found is to say:

context['context'] = context

in your view(s) that you want to display, and then in the template, you can say:

{% for c in context %}
<p>{{ c|pprint }}</p>
{% endfor %}

Or something along those lines.

The reason that the simple {{ context|pprint }} doesn’t output what you expect is because of the __repr__() method on the Context() object in Django.  It constructs a big huge string for you, when what you want is to let pprint do all the heavy lifting and indentation.

This entry was posted in General and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>