Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How to use environment variables in Django

2 min read

While working with web applications often we need to store sensitive data for authentication of different modules such as database credentials and API keys. These sensitive keys should not be hardcoded in the settings.py file instead they should be loaded with Environment variables on runtime.

An environment variable is a variable whose value is set outside the program, typically through a functionality built into the operating system. An environment variable is made up of a name/value pair.

Environment variables help us keep secrets (for example, Passwords, API tokens, and so on) out of version control, therefore, they are considered an integral part of the popular Twelve-Factor App Design methodology and a Django best practice because they allow a greater level of security and simpler local/production configurations.

Also, environment variables provide a greater degree of flexibility for switching between local development setup and production setup.

Therefore Adding environment variables is a necessary step for any truly professional Django project.

Creating Environment Variables

Create a .env file in the same directory where settings.py resides and add the following key-value pair inside the file.

SECRET_KEY=0x!b#(1*cd73w$&azzc6p+essg7v=g80ls#z&xcx*mpemx&@9$
DATABASE_NAME=db_name
DATABASE_USER=db_user
DATABASE_PASSWORD=password
DATABASE_HOST=localhost
DATABASE_PORT=5432

Installing django-environ

We will use django-environ for managing environment variables inside our project. So let's install the package.

pip install django-environ

Using Environment Variables 

With that now, we can access the environmental variables in our codebase.

import environ

env = environ.Env()
# reading .env file
environ.Env.read_env()

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env("SECRET_KEY")

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

Save the file and run the server everything should be working smoothly.

Additionally, you can also provide default values as follows.

SECRET_KEY = env("SECRET_KEY", default="unsafe-secret-key")

Don't forget to add .env in your .gitignore also, it's advisable to create a .env.example with a template of all the variables required for the project.


DJANGO

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read