Preventing cross-site scripting attack on your Django website

Cross-site scripting (XSS) is a security exploit which allows an attacker to inject into a website malicious client-side code. The attacker can do some undesirable things like adding false content or spy on visitors to steal their personal information.

According to the Open Web Application Security Project, XSS was the seventh most common Web app vulnerability in 2017. Since XSS is such a common flaw in websites, browsers have added features to detect and prevent it in some cases, bundled in their 'XSS Auditors'. 

Using the X-XSS-Protection header with 'block' mode can provide extra security. Although these protections are largely unnecessary in modern browsers when sites implement a strong 'Content-Security-Policy' that disables the use of inline JavaScript ('unsafe-inline').

X-XSS-Protection: 1; mode=block enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected. 

In Django, this header is already present, we just need to activate it. You can see it in warnings if you run the command check --deploy.

?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'x-xss-protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks.

To enable the above header, you need to:

1. Make sure is present in middleware's list and is at the top. 2. Add SECURE_BROWSER_XSS_FILTER = True in your settings file.

Once these settings are enabled, you can see x-xss-protection header in the response headers.

xss in django

For the demo of blocking malicious script, visit this page.

Host your Django app for free.



How to generate ATOM/RSS feed for Django website

In previous articles, we learned how to create a sitemap for the Django website. A valid sitemap increases your website's search engine ranking. Hence good for search engine optimization. 

Similarly, adding a robot.txt file is good for your website. It tells crawlers, which page to crawl and which page not to crawl for indexing.

In this article, we will see how to generate RSS feed on your Django website. 

The RSS feed help to keep up readers with their favorite blogs, news sites, and other websites. RSS allows the content and new updates to come to the reader. Generally, you use RSS to syndicate or subscribe to the feed of a website, blog or almost any media content that is updated online

Create a file in your app directory, parallel to file and name it Paste the below code in it. 

In the below sample example, we are fetching posts/articles from the database of We have implemented four methods, item, item_title, item_description and item_link. The code has been updated with comments.

class LatestEntriesFeed(Feed):
title = " New article for Python programmers every week"
link = "/feed/"
description = "Updates on changes and additions to python articles on"
# return 10 recently created/updated posts
def items(self):
return get_recent_updated_posts(number_of_posts=10)

def item_title(self, item):
return item.title
# return a short description of article
def item_description(self, item):
return item.description
# create and return the article URL
def item_link(self, item):
return reverse('appname:index', args=(item.post_id,))

Now in your project's file (not in any app's file) add below code.

from appname.feeds import LatestEntriesFeed()

# add feeds path
urlpatterns += [
path(r'feed/', LatestEntriesFeed()),

Restart/Reload your Django app and go to or localhost:8000/feed/.

You can validate if RSS feed generated is valid or not.

How to create sitemap of Django website

A site map is a list of a website's content designed to help both users and search engines navigate the site.

A site map can be a hierarchical list of pages, an organization chart, or an XML document that provides instructions to search engine crawl bots.

Why sitemaps are required:

XML Sitemaps are important for SEO because they make it easier for Google to find your site's pages—this is important because Google ranks web PAGES, not just websites. There is no downside of having an XML Sitemap and having one can improve your SEO, so we highly recommend them.


The sitemap for this blog can be found at . 

creating sitemap of dynamic urls in your django application

Steps to add Sitemaps to your Django Application:

Create a file in your app.

Create two different classes in file, one for static pages and another for Dynamic URLs.

Let's assume your website sell some product where product details are stored in the database. Once a new product is added to the database, you want that product page to be searchable by search engines. We need to add all such product pages/URLs to sitemaps.

Static Sitemap:

Define a class StaticSitemap in your file. Define the mandatory function items in it which will return the list of objects.

These objects will be passed to the location method which will create URL from these objects. 

from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse

class StaticSitemap(Sitemap):

    def items(self):
        return [

    def location(self, item):
        return reverse(item)

Here in items function, we are returning appname:url_name which will be used by the location method to convert into an absolute URL.

Refer you app's file for URL names.

Dynamic Sitemap:

Similarly, we will create Dynamic sitemap by fetching values from DB. 

from mystore.models import ProductDetailsModel

class ProductSitemap(Sitemap):

    def items(self):
        return ProductDetailsModel.objects.all()

    def location(self, item):
        return reverse('myapp:product', args=[item.product_id])

Here we are getting all products from the database and generating URLs like

Adding sitemaps in URLconf:

Now add these sitemap class in URLconf. Edit the project's  file and add below code in it.

from mystore.sitemap import  StaticSitemap, ProductSitemap
from django.contrib.sitemaps.views import sitemap

sitemaps = {
 'pages': StaticSitemap,
 'products': ProductSitemap,

urlpatterns += [
    url(r'^sitemap.xml$', sitemap, {'sitemaps': sitemaps})


Now reload your server and go to localhost:8000/sitemap.xml and you will be able to see your sitemap there.  

Reference :   

Host your Django App for Free.

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© 2018-2019
Contact Us: code108labs [at]
Address: 3747 Smithfield Avenue, Houston, Texas