views:

104

answers:

1

Am I doing this right? (probably not...someone correct? thanks)

@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
    return text.replace('\'','\\'')


{{ query|addslashes }}
+2  A: 

There is a builtin filter with the exact same name: addslashes

It also escapes double quotes, and double slashes. If you only want single quotes, you will have to adapt it and name it differently.

Here is how the original works:

def addslashes(value):
    """
    Adds slashes before quotes. Useful for escaping strings in CSV, for
    example. Less useful for escaping JavaScript; use the ``escapejs``
    filter instead.
    """
    return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
addslashes.is_safe = True
addslashes = stringfilter(addslashes)
stefanw