Ticket #6748: safe-queryset-debug-v2.patch

File safe-queryset-debug-v2.patch, 2.0 KB (added by Kenneth Arnold, 17 years ago)

Revised, simplified version of the patch

  • views/debug.py

     
    474474                {% for var in frame.vars|dictsort:"0" %}
    475475                  <tr>
    476476                    <td>{{ var.0|escape }}</td>
    477                     <td class="code"><div>{{ var.1|pprint|escape }}</div></td>
     477                    <td class="code"><div>{{ var.1|safe_pprint|escape }}</div></td>
    478478                  </tr>
    479479                {% endfor %}
    480480              </tbody>
  • template/defaultfilters.py

     
    793793        return u"Error in formatting: %s" % force_unicode(e, errors="replace")
    794794pprint.is_safe = True
    795795
     796from pprint import PrettyPrinter
     797class SafePrettyPrinter(PrettyPrinter):
     798    '''A PrettyPrinter that will never evaluate an unevaluated QuerySet.'''
     799    def format(self, object, *a, **kw):
     800        from django.db.models.query import QuerySet
     801        if isinstance(object, QuerySet):
     802            object = object.query.as_sql()
     803        return PrettyPrinter.format(self, object, *a, **kw)
     804
     805def safe_pprint(value):
     806    """A wrapper around pprint that ensures that QuerySets don't get evaluated.
     807    If the QuerySet results have already been used, they will be cached and the
     808    result will be identical to normal pprint. However, if the QuerySet has not
     809    been used, this filter will return the SQL that the QuerySet would execute."""
     810    pp = SafePrettyPrinter()
     811    return pp.pformat(value)
     812   
     813
    796814# Syntax: register.filter(name of filter, callback)
    797815register.filter(add)
    798816register.filter(addslashes)
     
    831849register.filter(random)
    832850register.filter(rjust)
    833851register.filter(safe)
     852register.filter(safe_pprint)
    834853register.filter('slice', slice_)
    835854register.filter(slugify)
    836855register.filter(stringformat)
Back to Top