django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty

时间:2021-09-16 15:49:24

https://www.e-learn.cn/content/wangluowenzhang/165461

问题:

I created a new project in django and pasted some files from another project. Whenever I try to run the server, I get the following error message:

Here's my settings.py

Here's manage.py as well

Any help? Thanks!

回答1:

Just like the error says, you have no SECRET_KEY defined. You need to add one to your settings.py.

Django will refuse to start if SECRET_KEY is not set.

You can read more about this setting in the docs.

The SECRET_KEY can be just about anything...but if you want to use Django to generate one, you can do the following from the python shell:

Copy the SECRET_KEY to your settings file.

回答2:

SECRET_KEY variable in settings.py should be kept secret

You can place the string secret key generated with the get_random_stringfunction above (as said @rnevius ) in settings.py but use a function that get the variable.

This means, that for security reasons, it is better to hide the content of SECRET_KEY variable.

You can define an environment variable as follow:

In your $HOME/.bashrc or $HOME/.zshrc or /etc/bashrc or /etc/bash.bashrc according to your unix operating system and terminal manager that you use:

you can look something like this:

And in the settings.py you can add this:

The function get_env_variable tries to get the variable var_name from the environment, and if it doesn’t find it, it raises an ImproperlyConfigured error. Using it in this way, when you try to run your app and the SECRET_KEY variable is not found, you will be able to see a message indicating why our project fails.

Also you can protect the secret content variables of the project in this way.