Updated May 20, 2023
Introduction to Django Environment Variables
Environment variables allow setting the Django application configurations. So, when configuration level values need to be updated, the environment level variable plays a significant role. The key aspect of these environment variables is their capability to set the configurations for the elements. Furthermore, these configurations are designed to ensure that values can be securely hidden. Hence, this helps to hide the values and secure the variable and associated configuration items. The upcoming sections of the article discuss some key environment-level variables.
How do Environment variables work?
Below are the environment variables in the Django application,
1. DATABASE_URL: The database url variable is useful in supplying the database connection information.
DATABASE_URL= postgres://user:%[email protected]:3306/dbname
2. EMAIL_CONFIG: The database url variable is useful in supplying the database connection information.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 597
EMAIL_HOST_USER = #email id of sender
EMAIL_HOST_PASSWORD = #password associated to this email id
3. SQLite URLs: This is another exciting aspect to be discussed and considered for the open discussion of how environment-level variables help set the values. File-oriented database connectivity can be established through SQLITE URLS; from the database perspective, the corresponding format of the URL can be used for not considering the hostname and mentioning the portion of the “file” as the name of the database.
4. Nested lists: Nested lists are useful in applications that involve DJANGO ADMINS entries; The nested lists section provides a sophisticated way to manage these entries.
# DJANGO_ADMINS=John:[email protected],Jane:[email protected]
ADMINS = [x_value.split(':') for x_value in env.list('DJANGO_ADMINS')]
# or use more specific function
from email.utils import getaddresses
# DJANGO_ADMINS=Full Name <[email protected]>,[email protected]
ADMINS = getaddresses([env('DJANGO_ADMINS')])
5. Multiline value: It allows the set of variable values in more than one line. This aspect is worth discussing and considering for an open discussion on how environment-level variables are useful for setting values. So this extends the setting of variable values for more than a single line involved. Therefore, multiple lines will be associated and utilized, allowing various lines to be included as part of the process.
6. proxy value: This is exciting; applications allow prefixing the variable value. In Django, it is possible to prefix the value of a specific variable. This aspect is worth discussing and considering for an open discussion on how Django environment-level variables are useful for setting the values.
Examples
1. Settings.py:
Code:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
Template_DIR = os.path.join(BASE_DIR,'Templates/Mainpage')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-3w2sc%ysj3y-v4&kdl7@o$fz_f5(-d0b(cra_rdk*m7n$+w^8s'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'matrimony_pages',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'Matrimony.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [Template_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'Matrimony.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
CACHES = { 'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
} }
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
#STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ]
#print(STATICFILES_DIRS)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
#print(STATIC_ROOT)
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
2. Changes in Models.py file:
Code:
from django.db import models
# Model variables
# Create your models here.
class Object(models.Model):
Environment_Variable_Example_name = models.CharField(max_length=200,null=True)
Environment_Variable_Example_thegai = models.CharField(max_length=200,null=True)
Environment_Variable_Example_State = models.CharField(max_length=50,null=True)
Environment_Variable_Example_District = models.CharField(max_length=50,null=True)
Environment_Variable_Example_Address = models.TextField(null=True)
Environment_Variable_Example_Phone = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_profession = models.CharField(max_length=200,null=True)
Environment_Variable_Example_salary = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Rasi = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Phone = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_profession = models.CharField(max_length=200,null=True)
Environment_Variable_Example_salary = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Rasi = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Phone = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_profession = models.CharField(max_length=200,null=True)
Environment_Variable_Example_salary = models.BigInteger_Example_Field(null=True)
Environment_Variable_Example_Under_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Under_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Rasi = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Nakshatra = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Post_Graduation_Degree = models.CharField(max_length=200,null=True)
Environment_Variable_Example_Post_Graduation_college = models.CharField(max_length=400,null=True)
Environment_Variable_Example_Rasi = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
]
Ex: views.py
@login_required
def Environ_var_page(request,pk):
dict_var_ = {}
Environ_var_name = Key_details.name
Environ_var_Age = Key_details.age
Environ_var_Thegai = Key_details.thegai
Environ_var_state = Key_details.State
Environ_var_district = Key_details.District
Environ_var_Address = Key_details.Address
Environ_var_Phone = Key_details.Phone
Environ_var_Profession = Key_details.profession
Environ_var_Salary = Key_details.salary
Environ_var_UG = Key_details.Under_Graduation_Degree
Environ_var_UGC = Key_details.Under_Graduation_college
Environ_var_PG = Key_details.Post_Graduation_Degree
Environ_var_PGC = Key_details.Post_Graduation_college
Environ_var_UG = Key_details.Under_Graduation_Degree
Environ_var_UGC = Key_details.Under_Graduation_college
Environ_var_PG = Key_details.Post_Graduation_Degree
Environ_var_PGC = Key_details.Post_Graduation_college
Environ_var_Rasi = Key_details.Rasi
Environ_var_Nakshatra = Key_details.Nakshatra
dict_var_['Age'] = Environ_var_Age
dict_var_['name'] = Environ_var_name
dict_var_['thegai'] = Environ_var_Thegai
dict_var_['State'] = Environ_var_state
dict_var_['district'] = Environ_var_district
dict_var_['Address'] = Environ_var_Address
dict_var_['Phone'] = Environ_var_Phone
dict_var_['profession'] = Environ_var_Profession
dict_var_['Under_Graduation_Degree'] = Environ_var_UG
dict_var_['Under_Graduation_college'] = Environ_var_UGC
dict_var_['Post_Graduation_Degree'] = Environ_var_PG
dict_var_['Post_Graduation_college'] = Environ_var_PGC
dict_var_['Rasi'] = Environ_var_Rasi
dict_var_['Nakshatra'] = Environ_var_Nakshatra
dict_var_['State'] = Environ_var_state
dict_var_['district'] = Environ_var_district
dict_var_['Address'] = Environ_var_Address
dict_var_['Phone'] = Environ_var_Phone
dict_var_['profession'] = Environ_var_Profession
dict_var_['Under_Graduation_Degree'] = Environ_var_UG
dict_var_['Under_Graduation_college'] = Environ_var_UGC
dict_var_['Post_Graduation_Degree'] = Environ_var_PG
dict_var_['Post_Graduation_college'] = Environ_var_PGC
dict_var_['Rasi'] = Environ_var_Rasi
dict_var_['Nakshatra'] = Environ_var_Nakshatra
print(Key_details.Creator)
print(dict_var_)
return render(request,'Profilepage.html',dict_var_)
Output:
Conclusion
The above article depicts a clear idea of what environment variables are and how the environment variables work. More specifically, the use of Django Environ. The article further explains the various environment variables involved in Django and how they can be utilized. It provides suitable examples to illustrate their usage.
Recommended Articles
We hope that this EDUCBA information on “Django Environment Variables” was beneficial to you. You can view EDUCBA’s recommended articles for more information.