Skip to content

Instantly share code, notes, and snippets.

@IanoNjuguna
Created January 10, 2023 19:51
Show Gist options
  • Save IanoNjuguna/48c2251e15617894823e0bd45ff0e768 to your computer and use it in GitHub Desktop.
Save IanoNjuguna/48c2251e15617894823e0bd45ff0e768 to your computer and use it in GitHub Desktop.
Create a Virtual Environment

Create a Virtual Environment

It is suggested to have a dedicated virtual environment for each Django project, and one way to manage a virtual environment is pipenv or venv, which is included in Python.

With venv, you can create a virtual environment by typing this in the command prompt, remember to navigate to where you want to create your project.

Windows:

py -m venv myproject

Unix/MacOS:

python -m venv myproject

This will setup a virtual environment. Then you have to activate the environment, by typing this command:

Windows:

myproject\Scripts\activate.bat

Unix/MacOS:

source myproject/bin/activate

Once the environment is activated, you will see this result in the command prompt:

Windows:

(myproject) C:\Users\Your Name>

Unix/MacOS:

(myproject) ... $

Note: You must activate the virtual environment every time you open the command prompt to work on your project.

Install dependencies

Ensure you have python running on your machine.

pip install -r requirements.txt

Run

Open the terminal in the main directory and run

python manage.py runserver

.env

Store sensitive data in the .env file

The .env file will be hidden automatically from the repo because it should contain sensitive information of the project such as the SECRET_KEY. After cloning the repo go on and follow these steps:

  • In the root directory of this Project, (Inside the folder named community), create a file called .env
  • After creating the file, write the following lines:
  • 1. SECRET_KEY=your_secret_key
    2. DEBUG=True
  • This should do the trick, try running the server to check for any errors after creating your .env file
  • python manage.py runserver

Note Generating Your Own SECRET_KEY

To generate a new key, use the get_random_secret_key() function present in the django.core.management.utils that returns a 50 character string of random characters. You can open the python shell by typing this command first to execute the get_random_secret_key

python manage.py shell

After opening shell, execute the following code to generate your random key

>>>from django.core.management.utils import get_random_secret_key
>>>print(get_random_secret_key())

Copy the key generated and place it in your SECRET_KEY variable in the .env file. There should be no whitespace around the variable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment