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

Introduction

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 manage.py ​1​ file.

SECRET_KEY=il_tuo_secret_key
 DEBUG=True
 DATABASE_URL=postgres://user:password@localhost:5432/mydatabase

Django configuration

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

import environ

 env = environ.Env()
 environ.Env.read_env()

 SECRET_KEY = env('SECRET_KEY')
 DEBUG = env.bool('DEBUG', default=False)
 DATABASE_URL = env.db('DATABASE_URL')

Access to Environment Variables

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

Conclusion

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.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
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.