You may have encountered the error 'ImproperlyConfigured("The SECRET_KEY setting must not be empty."'. Starting a django project with improperly configured settings may result in an ImproperlyConfigured Error. To solve this error we must properly configure the settings file in our django projects especially projects that are open source from other developers who use environment variables to set settings values. To solve this problem we will go over the details of the SECRET_KEY settings, how to configure and good practices with examples
ImproperlyConfigured:The SECRET_KEY setting must not be empty #
To understand the problem, let us first look at the error message. Whenever we try to use invalid settings in a django application, most of the time it raises an ImproperlyConfigured exception from the django.core.exceptions.ImproperlyConfigured Exception. leaving out the secret_key variable is no exception to this since its a mandatory setting with its own rules. If the secret_key rules are not followed it will result in the following error.
Let's examine a case where the SECRET_KEY was improperly configured and the errors that you will get is an exception like this:
# in settings.py file set the SECRET_KEY to empty
SECRET_KEY = ""
We will encounter an error when we execute the code above. To understand this error, let us take one more example and see another case.
#in settings.py file
# delete the SECRET_KEY variable and try to access a random page
If we run this code, then we will get the following output:
File "/home/paulserian/Desktop/django_projects/.env/lib/python3.10/site-packages/django/conf/__init__.py",
line 101, in __getattr__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Since we left out the mandatory setting SECRET_KEY variable to empty in case 1 it will result in an error since the SECRET_KEY is used by django to process other things, we will go over the details later on. In case 2 django will also look for a SECRET_KEY variable and since it is not there it will raise the error again.
Reasons that will cause this error #
As stated earlier the django setting SECRET_KEY is mandatory and leaving it out or deleting it will definately raise an ImproperlyConfigured error. But why is this field mandatory?
To know why this setting must be used lets go over some of its uses in the django framework. First of all the django-admin startproject command will add a random string to the secret key variable for every new project you create and django will not start if the SECRET_KEY is not used.
The django SECRET_KEY IS used for:
- cryptographic signing unless a different key is provided
- all tokens for PasswordResetView
- all messages if CookieStorage or FallbackStorage is in use
- applied for all sessions if any other session backend other than django.contrib.backends.cache, or the default get_session_auth_hash() is in use
Secret Keys are not used for user passwords and rotating the key does not affect them
If a secret key is no longer set as SECRET_KEY or is not defined in SECRET_KEY_FALLBACKS all the above uses will no longer be valid.
When you want to rotate your secret key, the old key should be moved to the SECRET_KEY_FALLBACKS temporarily.
The Solution #
In general, the most obvius solution should be to include the SECRET_KEY variable in the settings.py file or use the randomly generated unique string
For convinience The settings.py file created by default using the django-admin startproject creates a unique SECRET_KEY
the next solution which is a production ready solution is using environment variables to set up the secret key used to hide the secret_key for security purposes.
The secret key should remain a secret always. The key used in production should not be the same as the one used during development for security purposes
Solution one
This is just a simple fix where you either leave the SECRET_KEY as generated by django-admin or you can use any random string on the variable.
Lets see an example
# in the settings.py file
SECRET_KEY = "some_strong_key_here"
The above solution will tell django to use the string we have provided as the secret key for all its tasks.
Reload the server and as try to access a page it will not raise the error again
Note: this method is not secure and you should generate a strong string using e.g uuid with a combination of environment variables for security
Solution two
In this solution we will get over how to use environment variables for production
Let's update the code. First we will need to install a module called environ that will be used for creation of environment variables. Lets start by installing environ using pip.
$ pip install django-environ
The code above will install environ for our use. lets get started with creating the variables
# in settings.py file
import environ
env = environ.Env(DEBUG=(bool, False)
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
SECRET_KEY = env('SECRET_KEY')
In the above code we first import the environ module which tracks the version of the package as well as bas e package info used by other functions within django-environ
In the Second line we instantiate the Env class which provide scheme-based lookups of environment variables so that each caller doesn't have to pass in cast and default parameters.
in the Third line the read_env method is used to read an env file into os.environ where we give it a path for the location of an env file.In this case we have provided the root dir
On the fourth line, env('SECRET_KEY') returns the value contained in the SECRET_KEY variable in the env file
The final step is creating a file called .env in the root of your project which will be read by read_env method. It will look as follows.
# .env file
SECRET_KEY=somesuperstrongstringvariable
After doing the above add the .env file to your gitignore if using git for security purposes and reload the server and your problem is fixed and secure.
The Conclusion
Thank you for following with this tutorial all the way to the end. When you are working with django we have seen that is is essential to be careful with the settings file else it will raise an ImproperlyConfigured Error. We have seen the error interms of invalid secret key settings. We have discussed the uses of the secret key and how to use it securely using environment variables. I hope this article helps whenever you come across this issue. Happy hacking