The goal of this tutorial is to guide you through the essential process of configuring the settings for your Django project. We will explore how to properly use the settings.py
file and manage environment variables.
By the end of this tutorial, you will be able to:
settings.py
file.This tutorial assumes that you have a basic knowledge of Python programming and Django. It also assumes that you have Django installed on your system.
Every Django project starts with a set of default settings, suitable for development but not for production. The settings.py file, located in your Django project directory, is responsible for holding all your project's configuration.
Open your settings.py
file. Here you see different configurations like DATABASES
, INSTALLED_APPS
, MIDDLEWARE
, etc. You can change these according to your project's requirements.
Environment variables are variables that are defined outside the program, usually in the operating system, to influence the program's behavior. It's a good practice to separate your code base from sensitive data like SECRET_KEY
, DATABASE_PASSWORD
, etc. We usually store such data in environment variables.
Let's say you want to add a Django app to your project. You can add it to the INSTALLED_APPS
in your settings.py
.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
...
'your_app_name', # Add your app name here
]
You can use the os
module to access environment variables in your settings.py
file. Let's say you want to access the SECRET_KEY
.
import os
SECRET_KEY = os.environ.get('SECRET_KEY', 'fallback_value')
The os.environ.get()
method will try to get the value of the SECRET_KEY
from environment variables. If it doesn't find it, it will use the 'fallback_value'.
In this tutorial, we learned about the Django settings and how to configure them according to our project's requirements. We also learned about environment variables and how to use them to separate sensitive data from our code base.
Next, you can learn more about Django settings and environment variables from the official Django documentation.
Try to change the DATABASES
configuration in your settings.py
to use a PostgreSQL database.
Set the DEBUG
variable in your settings.py
using an environment variable.
Create a new Django app and add it to your INSTALLED_APPS
list in settings.py
.
Remember, practice is the key to mastering any skill. Keep coding and exploring!