Este artículo todavía no está traducido. Estás leyendo la versión en English.

Storing configuration parameters in a .env file allows you to easily manage environment-specific settings such as database credentials, API keys, secret keys, and other sensitive information.

Password Protection in Django - A step-by-step guide

About password protection with .env (Postgres, MySQL, Mongodb)

Note that it is important to not hard-code passwords or secret keys in the settings.py file. You know that in DEBUG mode, the application will show information from the settings.py file to the browser and console when an error occurs, and from that, the sensitive information such as passwords will be expose to the public in general. That is why sensitive data should be stored in a .env file and make them available to read in the settings.py file instead of being stored there directly.  Now let us see how to get best practice while creating your Django web application.

In this article, I will share with you 4 ways to deal with a .env file in your Django application using: python-decouple or python-dotenv or django-environ or django-dotenv. Spoiler alert, you will see some repeated code but it is for detail each way completely.

1st way: Implement password protection with .env using python-decouple

We will use python-decouple for managing environment variables inside our project. So let us install the package: pip install python-decouple

  • Cd into your app folder (my Django project and app reside on a folder named src), so inside that src folder I create a file with the name .env using the terminal: touch .env
  • In the .env file, enter the following database settings as key=value pairs that include the credentials to your database, your Django secret key, and your email server configuration if you are sending email with Django:
# Database Settings
DB_NAME=your_db_name
DB_USER=postgres
DB_PASSWORD=your-database-password
DB_HOST=localhost
DB_PORT=5432

Note: I am using PostgreSQL server instead of the default sqlite3 database, and for that, I have installed the following to make it works:  pip install psycopg2-binary

 Or:

If you still use the default sqlite3 database, you can skip the database setting part or you can keep if to use latter.

# DJANGO SECURITY

SECRET_KEY='django-insecure-blablabla)blablabla-xxxxxxxxxxxxxx;-blablablablaxxxxxx)'

DEBUG=True

Follow the steps below to generate a Django secret key:

  • Access the Python Interactive Shell: python manage.py shell
  • Type the following: from django.core.management.utils import get_random_secret_key
  • Generate the Secret Key in the Terminal: print(get_random_secret_key())
  • Copy and Paste the Key into your SECRET_KEY variable in the .env file:
  • SECRET_KEY=t+)%$_pt0i2#jf1*&w*v-e$w!i+kjh##^w+mr9!@qttwsz_mx9
  • Exit the shell by typing: exit() or making: Ctrl+Z

Note: You can also generate Django secret key using: https://djecrety.ir/

  • In the settings.py file, look for the line where Path is imported from pathlib and beneath it, add this import: from decouple import config

·        Now update the DEBUG = True, to the following:

DEBUG = config('DEBUG', default=False, cast=bool)

·        Edit the settings.py to set the security:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
  • Edit the settings.py file to connect to the PostgreSQL server instead of the default sqlite database. In settings.py, scroll down to the DATABASES object, which you commented out in Task 1. Replace the commented-out object with the following:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
    }
}

      Note: 

1-     The config() function is imported, then used to set the values for the Django secret key, the database settings, and the email server configuration by retrieving them from the .env file we’ve created earlier. This decouples the Django secret key, the database settings, and the email server configuration from the settings.py file to improving the app security.

2-     I usually create another file named: .env.example in the project folder and push it on github to explain how to configure the .env file for the project. You can do the same using a README.md file.

o   The .env.example file:

# TO CONFIGURE THE APP AND MAKE IT WORK PROPERLY YOU CAN REPLACE THE FOLLOEING 
# WITH YOUR OWN SECURITY CODE AND PASSWORD
# Note that this configuration should be inside a file named .env 

# DJANGO SECURITY 
SECRET_KEY=django-insecure-blablabla)blablabla-xxxxxxxxxxxxxx;-blablablablaxxxxxx)
DEBUG=True

# Database Settings
DB_NAME=your_db_name
DB_USER=postgres
DB_PASSWORD=your-database-password
DB_HOST=127.0.0.1
DB_PORT=5432

3-     After creating a Git repository for your project, the .env file should also be included in a .gitignore file so that it is not added to the repository.

That's all, now you know how to protect your credentials using the famous python-decouple. In the next section we will do the same exercise using python-dotenv.

Note that we are using PostgreSQL server instead of the default sqlite3 database. If you want to use MySQL, or MongoDB, or Microsoft SQL, you will find the setting for each in the bonus section after the 4th way of our exercise.

2nd way: Implement password protection with .env using python-dotenv

We will use python-decouple for managing environment variables inside our project. So let us install the package:

pip install python-dotenv

  • Cd into your app folder (my Django project and app reside on a folder named src), so inside that src folder I create a file with the name .env using the terminal: touch .env
  • In the .env file, do the same as in part 1:
  • In the settings.py file do the following:

from dotenv import load_dotenv
import os
load_dotenv()

·        Edit the settings.py to set the security:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
  • Edit the settings.py file to connect to the Postgres server instead of the default sqlite database. In settings.py, scroll down to the DATABASES object, which you commented out in Task 1. Replace the commented-out object with the following:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': os.environ.get('DB_HOST'),
        'PORT': os.environ.get('DB_PORT'),
    }
}

That's all, now you should be able to use the famous python-dotenv.

BONUS

 In the previous exercises, we have setting up the database to connect to a PostgreSQL database and to do so, you need to install psycopg2 or psycopg2-binary or psycopg-binary and add the following in the settings.py file:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'adminbackend_db',
        'USER': 'postgres',
        'HOST': 'localhost',
        'PASSWORD': 'your-database-password',
        'PORT': '5433'
    }
}

 Now if you want to use MySQL, or MongoDB, or Microsoft SQL, the following instructions will show you how.

If you want to use MySQL instead of PostgreSQL
Download and install MySQL on your computer: 
-> https://www.mysql.com/downloads/
-> Click on: MySQL Community (GPL) Downloads »
-> Click on: MySQL Community Server
-> For Windows, click on the button: Go to download page
-> For Windows download the (mysql-installer-community) not the (mysql-installer-web)
-> Click on: No thanks just start my download.

After installing MySQL and other tools like DataGrip or Mysql Woekbench...
-> create a database for you app if not created already.
To do so in datagrip, open the Query Console and type: CREATE DATABASE database-name_db

To connect to your MySQL database:
•    In your Django project (venv) install mysqlclient: pip install mysqlclient
•    go to the settings.py file and update the DATABASE section:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "database-name_db",
        "HOST": "localhost",
        "USER": "root",
        "PASSWORD": "your-database-password",
        "PORT": 3306
    }
}

MongoDB database
To connect to your MongoDB database:
•    In your Django project (venv) install djongo & dnspython: pip install dnspython djongo 
•    Install the following also: pip install pymongo==3.12.3
•    go to the settings.py file and update the DATABASE section:
    DATABASES = {
    "default": {
        "ENGINE": "djongo",
        "NAME": os.environ.get("DB_NAME"),
        "ENFORCE_SCHEMA": False,
        "CLIENT": {
            "host": os.environ.get("DB_HOST"),
            "authMechanism": "SCRAM-SHA-1",  # For atlas cloud database
        },
    }
}

Microsoft SQL
Download and install Download SQL Server Management Studio (SSMS) on your computer: 
•    For more informations go the following web site, and follow the instructions: Learn More
•    (optional): or you can just search on Google for -> Download SQL Server Management Studio (SSMS) 

To connect to your SQL Server:
•    In your Django project (venv) install pyodbc: pip install pyodbc 
•    The documentation for pyodbc: See Documentation 
•    Install django-pyodbc-azure: pip install django-pyodbc-azure
•    To know more about django-pyodbc-azure: Learn More 
•    go to the settings.py file and update the DATABASE section:
    DATABASES = {
    "default": {
        "ENGINE": "sql_server.pyodbc",
        "NAME": "database-name_db",
        "HOST": "your-server.database.windows.net",
        "USER": "database-username ",
        "PASSWORD": "your-database-password",
"OPTIONS": {
            "driver": "ODBC Driver 19 for SQL Server ",
            "isolation_level": "READ UNCOMMITED"  # This line is preventing deadlocks
        }
    }
}

Hope you find this article interesting and practical. Enjoy your coding journey!

Yardley Estiverne
Yardley Estiverne
Desarrollador de MVP con IA y software | Emprendedor tecnológico en IA

Desarrollador de MVP con IA — desarrollador Blazor, C# .NET con una sólida experiencia práctica en el desarrollo y despliegue de soluciones web robustas. Competente en programación .NET y sus bibliotecas, así como en buenas prácticas de SQL. También creo aplicaciones backend con Django Rest Framework.

LinkedIn:Yardley

Sin comentarios