I have been working on some Django tasks for a while. I mistakenly pushed my secret key to my public GitHub repository.😬 Yeah, rookie mistake! 🤷🏽♂️
I immediately received an email from GitGuardian informing me of the security risks involved.
I took some steps to avoid this problem in subsequent tasks and projects. Before I get to that, I will briefly highlight some requirements.
P.S. I use VSCode on a windows device. 😁
Requirements
Use a .gitignore file.
A .gitignore file tells git what files and directories to ignore. Git will automatically ignore any file or directory put in this file to protect sensitive information.
Create .gitignore files at the root of your GitHub repository before you git-clone it to VSCode.
Create a virtual environment i.e. .env or .venv file.
#.env
py -3 -m venv .env
#.venv
py -3 -m venv .venv
- It is good practice to ignore your virtual environment by adding it into the .gitignore file, which you have included at the root of your repository.
Steps
On your command line, install python-dotenv with the following code:
pip install python-dotenv
Go to your settings.py file and paste these two lines in your settings file:
from dotenv import load_dotenv
load_dotenv()
Copy your secret key from your settings.py file and paste it into the .env or .venv file you created:
SECRET_KEY=ui#1j%%f5mxdojzakk72+dvftl%4&y#31_a##16s6s(6pfxy-b
Remove the spaces before and after the equal sign
Remove the quotation marks
Next, in your settings.py file, you retrieve the secret key as follows:
SECRET_KEY = str(os.getenv('SECRET_KEY'))
You may need to add the import os function:
Run the server to see if it works before you stage and commit:
python manage.py runserver
Note
I switched to Git Bash on VSCode. Some commands did not work as expected with other terminals.
You may decide to try out any other terminal provided by VSCode:
If you know other ways to solve this, kindly leave a comment. 👇🏽
Cheers! 🍻
References
https://www.freecodecamp.org/news/gitignore-what-is-it-and-how-to-add-to-repo/
https://dev.to/vladyslavnua/how-to-protect-your-django-secret-and-oauth-keys-53fl