Django | Part 2 | Installing Django
With the architecture around the website decided, it is now time to begin the initial stages of the build. In this article, I will go through installing and setting up Django locally before making some initial configurations to the settings.py file that will make our lives easier down the track.
To do this, you should already have:
- Python 3 is installed on your computer.
- A Google Cloud account. You can sign up with the following link and receive credits making it free for your first three months. https://cloud.google.com/free
- Have the Google cloud SDK installed on your computer and a default project configured. https://cloud.google.com/sdk/docs/install
First, open up Powershell or Terminal, and navigate to your working directory. Once there, you will need to create a virtual environment. Working from a virtual environment is essential for this project as it gives you a place to work independently from your main operating system. That way, you can ensure that there are no package conflicts with any other projects and that your development version will be the same as your production version when you deploy the project. To do this, enter the following code depending on whether you use a Windows computer or Mac/Linux.
Windows
# Create your new virtual environment
python -m venv venv
# Activate it so that you are working from it
venv/Scripts/Activate
Mac
# Create your new virtual environment
python -m venv venv
# Activate it so that you are working from it
source venv/bin/activate
Once you have done this, you should see the (venv) is active under your PowerShell or Terminal window.
Installing Django
Now that you are in your virtual environment, the next thing you need to do is install a fresh version of Django. At the time of writing, I am using Django version 4.1. You can use the python pip installer and the following command to do this.
#Update pip version (only needs to be done once)
pip install --upgrade pip
# Install Django version 4.1
pip install django==4.1
Now, still in Powershell or Terminal, you can use the newly installed Django package to create a new project. Creating the project will include a few core files and directories needed for the project to work correctly. You can do this with the following command.
#Create a Django project
django-admin startproject blog_website
#Navigate to the new project directory
cd blog_website
After this, technically you can run the shell website, however, there are a few additional steps that I like to take here to make life easier down the track.
To do this, open up your settings.py file in a text editor and make the following changes.
Generate a new secret key
The first thing that I do is generate a new secret key for the project. By default, the project already creates one for you, which you can see as the “SECRET_KEY” variable. You can create your own or visit one of the many Django key generator sites.
Set up a secret in Google Cloud
As best practice, I prefer not to have tokens, secrets, or other sensitive information hard-coded into the settings.py file. Instead, I store them as a secret in Google Cloud. Each time the server starts up, it will securely fetch them as environment variables.
For now, we only have one value there. As we progress through the project, we will add more.
-
Navigate to the Google Cloud secrets page. You will need to enable the API if it is your first time. https://console.cloud.google.com/security/secret-manager
-
Create a new Secret and call it django_settings
-
Add your newly created secret key in the value section (inserting your new key into the placeholder).
SECRET_KEY={SECRET_KEY}
Editing the settings.py file Now that the secret is set up, you need to modify the settings.py file to extract them from the Google Secret Manager. In addition, you need to create conditional logic that can easily switch between development and production modes. It may not seem necessary now, but it will save a lot of hassle once your application is in production.
First, import packages. Do this with the following code underneath the initial pathlib import.
import os
from urllib.parse import urlparse
import io
import environ
import google.auth
from google.cloud import secretmanager
Then set up an environment variable declaring DEBUG at the top, directly under the BASE_DIR variable. This boolean will be what you change to switch between the production and development environments. Note that it is currently set to true, meaning that DEBUG is on and you are not in production.
env = environ.Env(DEBUG=(bool, True))
env_file = os.path.join(BASE_DIR, ".env")
Next, paste the following code to load your secrets from Google Secret Manager and save them as environment variables. It also populates the following key variables; SECRET_KEY, DEBUG, & ALLOWED_HOSTS.
# Attempt to load the Project ID into the environment, safely failing on error.
try:
_, os.environ["GOOGLE_CLOUD_PROJECT"] = google.auth.default()
except google.auth.exceptions.DefaultCredentialsError:
pass
if os.path.isfile(env_file):
# Use a local secret file, if provided
env.read_env(env_file)
elif os.environ.get("GOOGLE_CLOUD_PROJECT", None):
# Pull secrets from Secret Manager
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
client = secretmanager.SecretManagerServiceClient()
settings_name = os.environ.get("SETTINGS_NAME", "django_settings")
name = f"projects/{project_id}/secrets/{settings_name}/versions/latest"
payload = client.access_secret_version(name=name).payload.data.decode("UTF-8")
env.read_env(io.StringIO(payload))
else:
raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.")
# [END cloudrun_django_secret_config]
SECRET_KEY = env("SECRET_KEY")
DEBUG = env("DEBUG")
if DEBUG:
ADMIN_ENABLED = True
else:
ADMIN_ENABLED = False
# [START cloudrun_django_csrf]
# SECURITY WARNING: It's recommended that you use this when
# running in production. The URL will be known once you first deploy
# to Cloud Run. This code takes the URL and converts it to both these settings formats.
CLOUDRUN_SERVICE_URL = env("CLOUDRUN_SERVICE_URL", default=None)
if CLOUDRUN_SERVICE_URL:
ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc]
CSRF_TRUSTED_ORIGINS = [CLOUDRUN_SERVICE_URL]
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
else:
ALLOWED_HOSTS = ["*"]
# [END cloudrun_django_csrf]
Lastly, delete the original placeholders for the SECRET_KEY, DEBUG, & ALLOWED_HOSTS variables before then saving your changes to the file.
Creating a requirements.txt file
In the project’s root directory, create a file called requirements.txt. This file contains all the necessary packages for the project to work correctly. You can use pip to read this file and install the listed packages and versions. Below are the required packages.
django==4.1
google-cloud-secret-manager==2.12.0
django-environ==0.9.0
Once you have saved this file, install them with the following command.
pip install -r requirements.txt
Setting the Google Cloud Project as an env variable and running the application
With the edits of the settings.py file complete and the necessary packages installed, Django will be successfully installed and configured for your blog project.
You can run it once you have declared your Google Cloud Project as an environment variable.
#Set your Google Cloud Project Id as an environment variable
set GOOGLE_CLOUD_PROJECT={MY_GCP_PROJECT}
#Run the Django Application
python manage.py runserver
And there you have it! You have successfully installed, configured and deployed your first Django project. The additional edits to the settings.py file may seem like extra effort now, but they will make your life much easier once your website is in production and you regularly change between environments. We will build these in future iterations by adding secrets for your production database, a directory for your static files, and the authentication for your email service.
In the next article, I will take you through some core Django concepts and components. These will help you understand how Django works before jumping into the rest of the blog build.