How to Use the .env File in Django: A Step-by-Step Guide

9 ott 2023 1 min di lettura
How to Use the .env File in Django: A Step-by-Step Guide
Indice dei contenuti


Managing environment variables safely is crucial in every Django project. The .env file helps us achieve this by keeping our secret configurations separate from the source code. In this guide, we will explore how to use .env file in Django to manage environment variables.

Installation of Dependencies

To get started, you need to install the django-environ or python-dotenv package. These packages make it easy to manage environment variables in Django.

pip install django-environ
 # or
 pip install python-dotenv

Creation of the.env file

Create a file called .env in the root directory of your Django project, at the level of your ​1​ file.


Django configuration

In your file, import the necessary functions and load the environment variables from the .env file.

import environ

 env = environ.Env()

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

Access to Environment Variables

You can now access your environment variables in Django using the env('NOME_VAR') syntax.


Using ".env" files in Django (or any application) is a game changer when it comes to managing settings and configurations. Makes your application more flexible and secure by separating configurations from code. Always remember to protect sensitive information and keep configurations as clear and simple as possible.

Buy me a coffeeBuy me a coffee

Supportaci se ti piacciono i nostri contenuti. Grazie.

Successivamente, completa il checkout per l'accesso completo a
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.