In this guide, we’ll learn how to use .env files in Django. .env files help keep our settings secure and organized. They store sensitive information like passwords and API keys. This way, we don’t have to put them directly in our code.

What are .env files?

.env files are simple text files used to define environment variables. They follow this format:


VARIABLE_NAME=value
ANOTHER_VARIABLE=another_value

With .env files, you can store settings like database credentials, API keys, and any other configurations that might change between environments.

Why Use .env Files?

  • Security: Keep sensitive data out of your code.
  • Organization: Store configuration settings in one place.
  • Flexibility: Easily change settings without changing the code.

Getting Started

  1. Install python-dotenv: This library helps us read .env files.
    
    pip install python-dotenv
    
    
  2. Create a .env File: In your project root, create a file named .env.
  3. Add Your Settings: Put your sensitive settings in the .env file.
    
    SECRET_KEY=your-secret-key
    DATABASE_URL=your-database-url
    
    

Using .env in Django

Update the settings.py to read the .env file in your Django settings.


import os
from dotenv import load_dotenv

load_dotenv()

SECRET_KEY = os.getenv('SECRET_KEY')
DATABASE_URL = os.getenv('DATABASE_URL')

Now, your Django project will use the settings from the .env file. This makes your project more secure and easier to manage.

That’s it! You’ve learned how to use .env files in Django.