How to print query result in python/django
<p>I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:</p>

<ul>
<li>A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.</li>
<li>A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.</li>
</ul>

<p>I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
<strong><em>app_name/views.py:</em></strong></p>

<pre><code>def detail(request, soc_id):
    soc = get_object_or_404(Soc, pk=soc_id)
    return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>

<p>How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.</p>

<p>I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)</p>

<pre><code>import pprint
def detail(request, soc_id):
    soc = get_object_or_404(Soc, pk=soc_id)
    pprint.pprint(soc)
    return render(request, 'socs/detail.html', {'soc': soc})
</code></pre>

<p>I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.</p>

<p>The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.</p>

<p>If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send <code>{'soc': soc}</code> to your template as context. Because of this, you should be able to use it in your template. So, in your template (<code>socs/detail.html</code>), just add <code>{{ soc }}</code> somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like <code>{{ soc.id }}</code>).</p>

<p>If you want to see everything that's in the object without specifying all of the different fields yourself, send <code>OBJECT.__dir__</code>. For example, for this you'd send <code>{'soc': soc.__dir__}</code> as your context. Keep in mind that this likely should not be used for anything but inspection on your part.</p>

<p>If you'd like to learn more about Django's templating, check out <a href="https://docs.djangoproject.com/en/1.10/topics/templates/#the-django-template-language" rel="nofollow">the syntax and more</a>.</p>

php python django cakephp pprint