How can I prevent SQL injection in PYTHON-DJANGO?

Viewed 28439

If a lamer input is inserted into an SQL query directly, the application becomes vulnerable to SQL injection, like in the following example:

dinossauro = request.GET['username']

sql = "SELECT * FROM user_contacts WHERE username = '%s';" % username

To drop the tables or anything -- making the query:

INSERT INTO table (column) VALUES('`**`value'); DROP TABLE table;--`**`')

What may one do to prevent this?

3 Answers

If you are using .extra() the syntax is:

YourModel.objects.extra(where=['title LIKE %s'], params=['%123%321%'])

Repeating here from this answer as this is hard to find, and the docs that say "you should always be careful to properly escape any parameters" do not go on to say how to properly escape them!

Related