In this tutorial we will learn how to your protect django
settings.py file of your project from being subjected to any attack. You can also find the code on GitHub.
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 settings.py file we find that there are some line of code like
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 settings.py is present).
In .env file we can have multiple variables, I have taken a few in my case.
PROJECT_SECRET=u6o#j(oc1ln24!5)sbl7*jgl^-#6+l9c^z88)[email protected])93$)k_ 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=127.0.0.1 (You can add multiple host separated by comma(,) ) EID=(Any email ID if you wanna add) EPASS=(Password)
After creating the
.env file we will add it in our
import os import environ env = environ.Env() environ.Env.read_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 else: DEBUG = False ALLOWED_HOSTS = [env("HOST")] ##If your settings.py is compromised one cannot see Allowed Hosts ## In Case you have any SMTP comfiguration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = env("EID") EMAIL_HOST_PASSWORD = env("EPASS")
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 – https://github.com/priyanshuarora1/Protecting-Django-Project-From-Getting-Attacked
Clone the Repository
git clone https://github.com/priyanshuarora1/Protecting-Django-Project-From-Getting-Attacked.git
Create Virtual Environment – VirtualEnv
Run requirements file to install libraries using pip
pip install -r requirements.txt
Run the server
python3 manage.py runserver
And open http://localhost:8000/ in your browser.