How it works...
As you can see, the local settings are not directly stored in settings.py, they are rather included via externally defined environment variables and evaluated in the settings.py file itself. This allows you to not only create or overwrite the existing settings, but also adjust the tuples or lists from the settings.py file. For example, we add debug_toolbar to INSTALLED_APPS here, plus its associated MIDDLEWARE, in order to be able to debug the SQL queries, template context variables, and so on.
Defining the values of these variables can be done in one of two ways. In development, we can declare them within runtime commands, as in the following:
$ DJANGO_USE_DEBUG=1 python3 manage.py runserver 8000
This sets the DJANGO_USE_DEBUG variable for this particular process, resulting in DEBUG=True in settings.py as per the examples listed earlier. If there are many variables to define, or the same values will be set every time the server starts, it may be handy to create a reusable script to do so. For example, in the development environment, we can create a dev shell script, such as the following:
#!/usr/bin/env bash
# bin/dev
# environment variables to be defined externally for security
# - MYSQL_USER
# - MYSQL_PASSWORD
# - MYSQL_ROOT_PASSWORD
DJANGO_USE_DEBUG=1 \
DJANGO_USE_DEBUG_TOOLBAR=1 \
MYSQL_HOST=localhost \
MYSQL_DATABASE=myproject_db \
python3 manage.py runserver 8000
Store the above in a bin directory alongside manage.py in your project, and make sure it is executable, as follows:
$ chmod +x bin/dev
Then, in a terminal, we can now start our development server, with all of the appropriate settings, as in the following:
$ MYSQL_USER=username MYSQL_PASSWORD=pass1234 bin/dev
The resultant runserver command will receive values not only for the MySQL username and password given here, but also all of the variables set in the dev script itself.