Protect Django Project From Getting Attacked

In this tutorial we will learn how to your protect django file of your project from being subjected to any attack. You can also find the code on GitHub.

Django Protect

So, let’s start.

Setting up Django Project

We will first create a Django Project. You can refer our previous blogs in order to create a django project.

In my case I have created a project name basic. Moving forward as we see our file we find that there are some line of code like SECRET_KEY ALLOWED_HOSTS or any gmail id or password that we use for SMTP and we don’t want anyone to see these credentials due to which our security may be compromised when the project is pushed on GitHub or deployed on any server. In order to protect them, we use environ to hide details from .

Setting up .env file in Django

Firstly we will install django environ

pip install django-environ==0.4.5

After installing environ we will create a .env file in the project folder (where is present).

In .env file we can have multiple variables, I have taken a few in my case.

DB_USER=(In case you have any DB on serverside)
DB_PASS=(DB Password)
ENV=production (You can change this to deployment when your project is hosted)
HOST= (You can add multiple host separated by comma(,) )
EID=(Any email ID if you wanna add)

After creating the .env file we will add it in our

import os
import environ

env = environ.Env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = env("PROJECT_SECRET") ##Project Secret is Hidden Now

if env('ENV')=="production":
    DEBUG = True
    DEBUG = False

ALLOWED_HOSTS = [env("HOST")] ##If your is compromised one cannot see Allowed Hosts

## In Case you have any SMTP comfiguration

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

Now, just add .env file in gitignore in order to protect env file to be shown on github, I have provided sample.env in github for demo.

Yes, that was all about to create an extra protection in you Django app.

GitHub – Run Example Locally

GitHub –

Clone the Repository

git clone

Create Virtual Environment – VirtualEnv

mkvirtualenv env

Run requirements file to install libraries using pip

pip install -r requirements.txt

Run the server

python3 runserver

And open http://localhost:8000/ in your browser.