Am I doing this right? (probably not...someone correct? thanks)
@register.filter('addslashes')
@stringfilter
def addslashes(text, arg):
return tex开发者_如何学运维t.replace('\'','\\'')
{{ query|addslashes }}
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)
精彩评论