[Django]-What is the best way to profile a view in Django?


three words: Django Debug Toolbar


The one project that meets all your requirements, with the exception of profiling, is the excellent django debug toolbar.

For standard profiling you need to use repoze.profile (which means you have to be running Django with WSGI interface such as mod_wsgi).

If you’re hardcore and need to debug memory leaks use dozer (also a WSGI component).


{% if debug %}
    <div id="debug">
        {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}
        {% ifnotequal sql_queries|length 0 %}
        (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
        {% endifnotequal %}
    <table id="debugQueryTable" style="display: none;">
        <col width="1"></col>
        <col width="1"></col>
        <th scope="col">#</th>
        <th scope="col">SQL</th>
        <th scope="col">Time</th>
        {% for query in sql_queries %}<tr class="{% cycle odd,even %}">
        <td>{{ forloop.counter }}</td>
        <td>{{ query.sql|escape }}</td>
        <td>{{ query.time }}</td>
        </tr>{% endfor %}
{% endif %}

Django Snippet: Template Query Debug


For people arriving in 2019+, django-debug-toolbar is still great, but just as a heads-up, most of the template profiling panes are broken in modern Django versions (2.0+).

Another good option these days is django-silk which has some beautiful timing profile visualization and graphing features, and django-live-profiler with a working fork for Django v2.0+ here.

Leave a comment