How to set up an env variable in django

How to set up an env variable in django

Environmental variables are a way to store and pass information between processes on a computer. They are commonly used to configure applications, including web frameworks such as Django.

In Django, environmental variables can be used to set up secrets, such as database passwords, that should not be stored in version control. They can also be used to set configuration options that may vary between different environments, such as a development or production server.

To set up an environmental variable in Django, you will need to first create a file called ".env" at the root of your Django project. This file should not be added to version control, as it may contain sensitive information.

In the ".env" file, you can set environmental variables in the format "VARNAME=value". For example:

SECRET_KEY=abcdefghijklmnopqrstuvwxyz
DATABASE_PASSWORD=123456

To load these variables into your Django project, you will need to use a library such as python-dotenv. You can install this library using pip:

pip install python-dotenv

Next, you will need to add the following code to your Django settings file to load the environmental variables from the ".env" file:

import os
from dotenv import load_dotenv

load_dotenv()

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

With these changes, your Django project will now be able to access the environmental variables you set in the ".env" file.

It is important to note that environmental variables should not be used to store sensitive information in production environments, as they can be accessed by anyone with access to the server. Instead, it is recommended to use a secure storage solution, such as a secret management service, to store sensitive information in production.

Overall, environmental variables can be a useful tool for configuring and managing applications, including Django projects. By following the steps outlined above, you can easily set up and use environmental variables in your Django projects.