addslashes Filter

Coding

Documentation

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.


Did we get something wrong? Is there a use case for the addslashes filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on March 26, 2023, 3:42 p.m. EST