Avoiding HTML injections and Cross Site Attacks on Input Fields
Django templates are often used to pass data to JavaScript code. Unfortunately, if implemented incorrectly, this opens up the possibility of HTML injection, and thus XSS (Cross-Site Scripting) attacks. This is one of the most common security problems I’ve encountered on Django projects. In fact I’ve probably seen it on every considerably-sized Django project, in some form or another. Also, not naming and shaming, but I’ve also seen it in lots of community resources. This includes conference talks, blog posts, and Stack Overflow answers. It’s hard to get right! It’s also been historically difficult, since it’s only Django 2.1 that added the json_script template tag to do this securely. (And the ticket was open six years!) Let’s look the problem and how we can fix it with json_script . The Vulnerable Way Let’s take this view: from django.shortcuts import render def index ( request ): mydata = get_mydata () return render ( reque...