How To Create And Use .env File in Django

Posted: September 29, 2024 | Updated: October 06, 2024

If you want to create a.env file and store your database information, follow this tutorial. 

Step 1: Install the Python decouple package.

First, install the Python decouple package using the following command.

pip install python-decouple

Step 2: Create a .env file and add the database information

Next, create a .env file In your project's root directory (where manage.py is located).

Add the following content to your env file and change the information based on your database.

# .env
DATABASE_NAME=your_db_name
DATABASE_USER=your_db_user
DATABASE_PASSWORD=your_db_password
DATABASE_HOST=localhost
DATABASE_PORT=5432

Save the .env file.

Step 3: In the settings.py file, add the following code

In your settings.py file, comment old database settings and add the following code.

import os
from decouple import config

# ...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': config('DATABASE_NAME'),
        'USER': config('DATABASE_USER'),
        'PASSWORD': config('DATABASE_PASSWORD'),
        'HOST': config('DATABASE_HOST'),
        'PORT': config('DATABASE_PORT'),
    }
}

Save the file and run the server.

Note: You can also add other details like SECRET_KEY, DEBUG in your .env file and use that info in your settings.py file. 

Ex: .env file

SECRET_KEY=Your security key
DEBUG=True

Usage in settings.py file 

DEBUG = config('DEBUG')
SECRET_KEY = config('SECRET_KEY')

Method 2: python-dotenv package

You can also install python-dotenv package to create and use a .env file. Simply call load_dotenv() at the beginning of your script.

Use the following command to install python-dotenv package.

pip install python-dotenv

Then create a .env file with database information and add the following lines in the settings.py file

from dotenv import load_dotenv
import os

load_dotenv()  # Loads the variables from .env file

DATABASE_NAME = os.getenv('DATABASE_NAME')

Use python-dotenv if:

  • You need a simple solution to load environment variables and don’t require additional features like type casting.
  • You prefer managing environment variables in a more traditional way.


Use python-decouple if:

  • You want more structured access to settings, including the ability to set defaults and cast types.
  • You’re looking for a clean separation between configuration and code.

© 2024 Webapptiv. All rights reserved.