Cross Site Scripting (XSS) Protection in Django
Last Updated :
15 Apr, 2024
Django protects your website from XSS attacks by employing CSRF tokens, unique for each user, hidden in forms. This article will show how to implement Cross-site scripting (XSS) protection in Django.
What is Cross-site scripting (XSS) Protection in Python Django?
In Django, they keep your website safe from XSS attacks by using CSRF tokens. These tokens are unique for each user and hidden in forms. When someone submits a form, Django checks if their token matches the one assigned to their session. This stops bad scripts from getting in, ensuring only legitimate users can interact with your site.
Implementation of Cross-Site Scripting (XSS) Protection in Django
Below, are the implementations of Cross-site scripting (XSS) protection Django in Python:
Starting the Project Folder
To start the project use this command
django-admin startproject xss_protected_project
cd xss_protected_project
To start the app use this command
python manage.py startapp xss_example
Now add this app to the ‘settings.py’
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"xss_example",
]
File Structure

Setting Necessary Files
views.py: Django view function, home
, renders a template named 'home.html'. If the request method is POST, it retrieves user input from the POST data. Otherwise, it defaults to a demonstration JavaScript code that triggers an alert, which is vulnerable to XSS attacks. To prevent such attacks, ensure proper sanitization and escaping of user input in HTML templates.
Python3
# xss_example/views.py
from django.shortcuts import render
def home(request):
if request.method == 'POST':
user_input = request.POST.get('user_input', '')
else:
# Default value for demonstration
user_input = "<script>alert('XSS attack!');</script>"
return render(request, 'home.html', {'user_input': user_input})
urls.py : Below are the urls.py file which connect views.py file to HTML file.
Python
# xss_protected_project/urls.py
from django.contrib import admin
from django.urls import path
from xss_example.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
]
Creating GUI
xss_example/templates/inde.html : HTML template, 'index.html', creates a form for user input with a textarea field. The form sends a POST request with the user's input. To mitigate XSS vulnerabilities, the user input is rendered using the safe
filter. However, it's crucial to sanitize and escape user input properly to prevent XSS attacks.
HTML
<!-- templates/inde.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XSS Example</title>
</head>
<body>
<h1>XSS Example</h1>
<form method="post">
{% csrf_token %}
<label for="user_input">User input:</label><br>
<textarea id="user_input" name="user_input" rows="4" cols="50">{{ user_input }}</textarea><br>
<input type="submit" value="Submit">
</form>
<p>Rendered user input:</p>
<!-- Displaying sanitized user input -->
<p>{{ user_input | safe }}</p>
</body>
</html>
Deployement of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Run the server with the help of following command:
python3 manage.py runserver
Output

Video Demonstration
Similar Reads
Prevent Cross-Site Scripting (XSS) in a Spring Application
Cross-site scripting is a popular and widespread attack, in which an adversary injects scripts into a web application. Web applications often use the same origination policy, which prevents scripts on the page from accessing data from different sources if their origins do not match Because Spring Bo
5 min read
How to Manage Local vs Production Settings in Django?
When developing a Django application, managing settings for different environments (local development, testing, staging, and production) is crucial for ensuring smooth deployment and security. You don't want the same settings (like debug mode or database credentials) for local development and produc
4 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Si
3 min read
Protecting sensitive information while deploying Django project
There will be a lot of sensitive information in our Django project resided in the settings.py, or local variables containing sensitive information or the POST request made using forms. So while deploying a Django project we always have to make sure they are protected especially the repositories that
3 min read
Django settings file - step by step Explanation
Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 min read
Top 10 VS Code Extensions For Python Django
Django is a popular web framework for building web applications using Python. In Visual Studio Code (VS Code), you can enhance your development workflow by using various Django extensions that provide helpful tools, features, and enhancements. Visual Studio Code (VS Code), a flexible and easily cust
6 min read
Setting Up a Virtual Environment in Django
Setting up a virtual environment in Django is essential for isolating your project's dependencies and ensuring consistent behavior across different environments. A virtual environment allows you to install packages locally without affecting the global Python installation. Here's how to set up a virt
2 min read
Create a new Django project in Pycharm using Pycharm Terminal
PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides many useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management
2 min read
Running Extra scripts in Django
Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always.It can be any script that may include a loading of data, processing, and cleaning of data, or any ML phase when making an application providing business logic
2 min read
What are transactions in Django?
In this article, we will explore the concept of transactions in Django, using a specific project as our reference point. We will delve into the process of executing transactions in Django and discuss the implementation of the same on the backend of the Django framework the end of this article, reade
10 min read