简体   繁体   中英

django form fields clean method and security

My web application has a lot of forms. I don't use django form classes, since my forms are somewhat complicated (involve with a lot of javascript), so I write the forms and handle them at server by myself.
My question is about "cleaning" the fields data. I know django forms has a clean() method which supposed to sanitize the data.
But isn't django built-in ORM already clean the data from SQL injection type attacks?

If I have similar code:

field = request.POST['field']
record = SomeModel.objects.get(pk=record_id)
record.field = field
record.save()

I POSTed a < script> tag with some javascript to my server, and I couldn't find any security hole here, since django sanitize the data that is printed in the template. so what the clean() method adds here exactly, and does this code has any security problems?

The clean() method mainly validates the form data ie it verifies if the data inserted in the form fields fits the type of the field and respects some patterns. The SQL injection protection is build into ORM. So if you use django ORM querysets you should be protected from SQL injection attacks. As per docs :

By using Django's querysets, the resulting SQL will be properly escaped by the underlying database driver.

Only if you want to run raw SQL or custom SQL queries you have to properly escape any parameters that the user can control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM