Home > Back-end >  Trying to hide django secret key, but getting error when deploying in PythonAnywhere
Trying to hide django secret key, but getting error when deploying in PythonAnywhere

Time:04-29

I'm trying to deploy a django project. I hid the secret key putting it in a file called .env and added it to .gitignore, so I have django's secret key only locally, and not in the git repository. But when I try to deploy the project in PythonAnywhere, an error occurs because there is no secret key in the repository (there is no file from where the server could read the secret key).

So I understand that it's not good to hard code the key, but how would I do to get a secret key for deployment?

I shouldn't have any secret key in the git repository, right?

CodePudding user response:

I shouldn't have any secret key in the git repository, right?

Right.

So I understand that it's not good to hard code the key, but how would I do to get a secret key for deployment?

The secret key can be stored as an environment variable or in a file that deploys alongside your project. Both options would have to be done through your host. Here's a Pythonanywhere suggestion for a file that deploys alongside your project: https://www.pythonanywhere.com/forums/topic/14207/

CodePudding user response:

You can have a separate .env file on PythonAnywhere to store a separate secret key. The .env file also a good place to store PythonAnywhere database passwords etc. Having a different file with different values locally and on PythonAnywhere makes sense from a security perspective. Don't forget to update your PythonAnywhere .gitignore file to include it if you ever upload to your git repository from PA!

You can create a new .env file in your project directory via the PA files section, and, using your local .env file as a base, generate a new key value either by:

$ python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"

or use a web tool like https://djecrety.ir/

  • Related