Published on

Django-environ : How to Use .env Files and Environment Variables in Django

Authors

Table of contents

Introduction

Django is a powerful web framework that allows developers to quickly build web applications. However, when working with Django, it is important to manage sensitive information such as database credentials, secret keys, and API keys. One way to manage this information is by using environment variables. In this blog post, we will explore how to use .env files and environment variables in Django using the django-environ package.

What is a .env file and Environment Variables

The .env file is a simple text file that contains environment variables. It is used to store sensitive information that should not be committed to version control. Environment variables are dynamic values that can be used by the application during runtime. They can be set on the operating system level or defined in the .env file.

This is what a .env file looks like :

DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=ADMIN
DB_PASSWORD=MySecretP4ssw0rd

Why should I use Environment Variables ?

Glad you asked. Using environment variables has several benefits, including:

  • Enhanced security by keeping sensitive information separate from the codebase.
  • Flexibility by allowing developers to easily switch between different environments without modifying the code.
  • Scalability by making it easy to deploy the application to different servers.

In this blog post, we will explore the benefits of using environment variables and explain how to use them in a Django application using Django-Environ library.

By the end of this tutorial, you will have a solid understanding of how to use .env files and environment variables in your Django application to keep your sensitive information secure and your application scalable.

Getting started with Django environment variables

What is django-environ?

django-environ is a third-party package for Django that allows you to read environment variables from .env files. This package makes it easy to manage sensitive information in your Django project.

How to Install django-environ?

You can install django-environ using pip. Open your terminal and run the following command:

pip install django-environ

Now that we have installed django-environ, let's move on to how to use it in our Django project.

  1. Creating a .env File

The first step is to create a .env file in the root directory of your Django project. This file will contain all the sensitive information that you want to store as environment variables.

Here's an example of what your .env file might look like:

SECRET_KEY='your_secret_key'
DATABASE_URL='your_database_url'
API_KEY='your_api_key'
DEBUG=True
  1. Updating Settings.py file

Next, we need to update the settings.py file to read the environment variables from the .env file. We can do this by importing the environ function from the django-environ package and calling it to read the variables from the .env file. Here's an example of how to update your settings.py file:

import environ

env = environ.Env()

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

SECRET_KEY = env('SECRET_KEY')

DATABASES = {
    'default': env.db(),
}

API_KEY = env('API_KEY')

DEBUG = env.bool('DEBUG', default=False)

In the code above, we first import the environ function from the django-environ package. We then create an instance of the Env class and call the read_env method to read the environment variables from the .env file. Finally, we use the env function to retrieve the values of the environment variables.

  1. Using Environment Variables in Your Code

Now that we have set up our .env file and updated our settings.py file, we can use the environment variables in our code. Here's an example of how to use the API_KEY environment variable in your views.py file:

from django.shortcuts import render
import requests
import environ

env = environ.Env()

def get_data(request):
    api_key = env('API_KEY')
    response = requests.get('https://api.example.com/data', headers={'Authorization': f'Bearer {api_key}'})
    data = response.json()
    return render(request, 'data.html', {'data': data})

In the code above, we import the environ function from the django-environ package and use it to retrieve the value of the API_KEY environment variable. We then make an API call using the requests library and pass the API_KEY in the Authorization header.

Frequently Asked questions

What are environment variables?
Environment variables are variables that are set in the operating system's environment and can be accessed from any program running on the system. These variables are used to store sensitive information such as API keys, database credentials, and secret keys.

What is django-environ?
django-environ is a third-party package for Django that allows you to read environment variables from .env files. This package makes it easy to manage sensitive information in your Django project.

How do I install django-environ?
You can install django-environ using pip. Open your terminal and run the following command:

pip install django-environ

How do I create a .env file?
To create a .env file, open a text editor and save a new file with the name ".env" in the root directory of your Django project. This file will contain all the sensitive information that you want to store as environment variables.

How do I update the settings.py file?
In the settings.py file, first import the environ function from the django-environ package. Then create an instance of the Env class and call the read_env method to read the environment variables from the .env file. Finally, use the env function to retrieve the values of the environment variables.

How do I use environment variables in my code?
You can use the environ function from the django-environ package to retrieve the value of the environment variables. Once you have retrieved the value, you can use it in your code just like any other variable. For example, you might use an API key in an Authorization header when making an API call.

Conclusion

And that's it. Now you know how to keep your credentials and sensitive constants a secret by using environment variables. By following the steps outlined in this blog post, you can ensure that your Django project is secure and your sensitive information is protected.