Jeswin-8802
Jeswin-8802

Reputation: 1

Running a Django application from a cloned repository that has environment variables

I'm trying to run a Django application from a cloned repository and I noticed that it has environment variables stored in the settings.py file(namely: the SECRET_KEY and DEBUG).

When running the application, it gives me the following error:

django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

I understand that Django cannot run without it but I have the following doubts regarding this problem.

Should I provide my own SECRET_KEY and declare it inside a .env file.

Also, is it necessary to have the same SECRET_KEY as the original project file did?

Upvotes: 0

Views: 511

Answers (3)

xB0t
xB0t

Reputation: 9

python-decouple is the alternative for django-environ , in case if you get any error using django-environ.

STEP 1 :- pip install python-decouple

STEP 2 :- open settings.py file

STEP 3 :- Import the config object:

from decouple import config

STEP 4 :- Retrieve the configuration parameters:

SECRET_KEY = config('SECRET_KEY')

STEP 5 :- create a .env text file in your repository’s root directory in the form:

SECRET_KEY=YOUR_SECRET_KEY

Note :- Remember , in .env file don't give spaces .

Visit :- https://pypi.org/project/python-decouple/ for more detailed explaination & documentation.

Upvotes: -1

Code-Apprentice
Code-Apprentice

Reputation: 83557

Should I provide my own SECRET_KEY and declare it inside a .env file.

Yes, you can either set the required environment variable in the shell where you run the django server or put it in a .env file.

Also, is it necessary to have the same SECRET_KEY as the original project file did?

No, you don't need the same value as the original project did. SECRET_KEY is used to salt. SECRET_KEY is used for cryptographic siging in sessions, password reset tokens, etc. For more detials see the documentation. The only restriction is that you must maintain the same SECRET_KEY for an instance of the django app. Otherwise sessions and other signed data will be invaliated.

Upvotes: 1

fkay
fkay

Reputation: 161

First, welcome to SO!

Second, it's best practice to store the secret key and other sensitive information (database password and so on) in environment variables. However, if you're just cloning a repo to practice in your local machine, you can use the cloned one until you think about deploying and version control.

One way you can do that quite easy in my opinion is django-environ. Check it out: https://django-environ.readthedocs.io/en/latest/

Regarding your question about the secret key, there is a reason why it is called a secret key: keep it a secret! In development, it's somewhat fine to temporarily use the cloned one but always make sure to keep the key secret for production. If you use version control (such as Git) the .env file should not be included to avoid incidents.

Upvotes: 1

Related Questions