Adds backslashes before quotation marks to escape them.
Variable
blurb = "Where'd you get the coconuts?"
Template
{{ blurb|addslashes }}
Result
Where\'d you get the coconuts?
This is particularly useful when you need to include Django variables within JavaScript code. Consider the following:
Template
<button onclick="alert('{{ blurb }}')">Alert</button>
Result
<button onclick="alert('Where'd you get the coconuts?')">Alert</button>
This will result in a JavaScript bug as the apostrophe in Where'd
will close the JavaScript string. Using addslashes
will fix that:
<button onclick="alert('{{ blurb|addslashes }}')">Alert</button>
Result
<button onclick="alert('Where\'d you get the coconuts?')">Alert</button>
Notice that the apostrophe in Where'd
is now escaped.
Commentary
If you are writing raw SQL queries, do not use
addslashes
to escape single quotes. Use parameters instead.