Creating a Django Project on Linux
So we’re going to take a bit of a detour this week. I’ve still been working on the Rails / React version of my fantasy hockey app, and I’ve got some cool stuff to say about that, but I’m also really excited to have an interview for a back end position tomorrow for a company utilizing Python and Django. It’s been quite a while since I’ve worked with these, first learning them towards the start of my journey in software engineering (cue CS50 nostalgia). I started out yesterday working on some of the easy algorithms on leetcode.com, and then began trying to implement a Django version of my fantasy hockey backend. My goal for interview time tomorrow is to have finished the fetcher commands to seed the database with teams / games / players / events from the NHL’s stats API. So far I’ve seeded teams.
Anyways, for now we’re going to focus on setting up a Django project on Linux, specifically Ubuntu. That’s not exactly a whole lot of work, so we’ll talk about setting PostgreSQL as your database and, since this project will be an API, adding in the Django REST Framework. Next week I’ll try to dive into routing, models and serializers a bit. Needless to say, after learning a lot about Ruby on Rails in the Flatiron course, it’s really cool to get back to Python / Django and apply some of the more conceptual things I’ve learned there.
Step 1: Download Python
Since we’re talking about Ubuntu, if you’re updated you should already have Python! Just to be safe, type python3 --version
. The current version at the time of writing this is 3.8.5. If you don’t have Python, or you want to update to a newer version, use the following commands:
sudo apt-get update
sudo apt-get install python3.8
python3 --version -> Python 3.8.5 hopefully
Step 2: Create Virtual Environment and Install Django
I would reference this article at this step (and for step 3), as it helped me a bunch setting up this morning. I’ll try to briefly summarize though.
First thing is to create a virtual environment. It seems you can create this wherever you’d like, although the linked article suggests in your home directory. The following command creates the virtual environment in your current directory, substituting myvenv
for the name you’d like to call your virtual environment (I created mine in /home/username/venvs
):
python3 -m venv myvenv
Then run:
source myvenv/bin/activate
to start the virtual environment. (myvenv)
should now be prefixed to your prompt in the console. One other cool thing to note, you can use python
instead of python3
now, as python
references python3
in this virtual environment.
Step 3: Upgrade PIP and install Django
First upgrade pip:
python -m pip install --upgrade pip
Then create a requirements.txt
file inside myvenv
with the current version of Django(version 3.2.3 was current at the time of this writing) and install:
echo 'Django~=3.2.3' >> myvenv/requirements.txt
pip install -r myvenv/requirements.txt
At this point, you should have access to django-admin
, which is what we’ll use in the next step.
Step 4: Install and Configure PostgreSQL
PostgreSQL comes by default with Ubuntu, so you should already have it. If you don’t have it or would like to update, run the following commands:
sudo apt-get update
sudo apt-get install postgresql-12
From here you’ll need to configure PostgreSQL, and I’m really sorry but I haven’t done this in quite a while (I set it up on my system back during the Rails project) and don’t really feel comfortable writing about something I haven’t done recently. Here is a link to the documentation. If I remember correctly, it involves setting up a postgres user, which you’ll need later on, so make sure to remember the username and password.
Step 5: Create Django Project
Woohoo easy part! Navigate to the directory you’d like to save your project at and run the following command (replacing supercoolproject
with your super cool project name):
django-admin startproject supercoolproject
Provided the previous steps were completed correctly, this should create a directory with your new project. You should be able to run the development server now:
python manage.py runserver
Step 6: Add Modules
I mentioned a few things earlier that are going to change what we’re adding to the modules file, namely that I’m going to be using djangorestframework
and have some fetcher commands requiring requests
. The next step is to update requirements.txt
in the venv directory, so I’ll include what mine looks like and also what yours will look like if you don’t need either of those.
First navigate back to your virtual environment directory, for me:
cd ~/venvs/django-fantasy-hockey
Enter vim
and edit your requirements.txt
as follows:
If you don’t need djangorestframework
or requests
, use:
Django~=3.2.3
django-environ
psycopg2
If you do need these, use:
Django~=3.2.3
django-environ
djangorestframework
markdown
django-filter
psycopg2
requests
Quickly going over what we’re using here, django-environ
lets you set environment variables in your app and psycopg2
is the PostgreSQL database adapter for Python. djangorestframework
, markdown
, and django-filter
are all included in the djangorestframework
documentation, so I’ve included them, and requests
is used to send network requests in Python.
After you’ve updated your requirements.txt
, install again:
pip install -r myvenv/requirements.txt
Step 7: Configure settings.py and .env file
So there’s two big parts to settings.py
, and one small part, so lets get the small one out of the way first. If you’re going to use djangorestframework
, add 'rest_framework'
to your INSTALLED_APPS
. It should look like this now:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
The two other changes are going to be related to environment variables and PostgreSQL. Since there’ll be some things we don’t really want to share with people in our settings.py
file, we can use the django-environ
module to store these values in a .env
file, which will be included in our .gitignore
, and loaded as environment variables in settings.py
.
First, we need to import and set up environ
. Update settings.py
to start as follows:
from pathlib import Path
import environenv = environ.Env()
environ.Env.read_env()
From here, we’re going to want to create a .env
file and move some values there from settings.py
. First create .env
in the same directory as settings.py
. In the .env
file, we’re going to include the SECRET_KEY
from settings.py
, as well as database details that we should have from setting up our PostgreSQL server. After updating, your file should look like this (substituting your secret key, database name, database user and database password — host and port should be the same unless you’ve changed defaults):
SECRET_KEY=<YOUR SECRET KEY>
DATABASE_NAME=<YOUR DATABASE NAME>
DATABASE_USER=<YOUR DATABASE USER>
DATABASE_PASSWORD=<YOUR DATABASE PASSWORD>
DATABASE_HOST=/var/run/postgresql
DATABASE_PORT=5432
Last, in settings.py
, we’re going to replace SECRET_KEY
and DATABASES
with the following:
Secret Key:
SECRET_KEY = env('SECRET_KEY')
Databases:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env('DATABASE_NAME'),
'USER': env('DATABASE_USER'),
'PASSWORD': env('DATABASE_PASSWORD'),
'HOST': env('DATABASE_HOST'),
'PORT': env('DATABASE_PORT')
}
}
This will hide things we don’t want to share on GitHub and configure PostgreSQL as our project database.
Step 8: Create a .gitignore and Push to GitHub
Last thing, if we pushed to GitHub right now, our .env
file would be included and that’d be bad. Lets create a .gitignore
file in our main project directory (the one above the one holding settings.py
). At the bare minimum, you need to have .env
included in this file, but I’d suggest using a template. People that know a lot more about this stuff have written them, so here’s a template you can use (this is the one I used). BIG NOTE IF YOU’RE USING THIS TEMPLATE: .env
is commented out. Please uncomment .env
so your secret key won’t be on GitHub (that’d be bad, mkay).
At this point, you should be safe to push to GitHub!
So yeah, that’s about where I was halfway through yesterday. Next week I’ll update on where I’m at, and at the very least walk through the basics of starting up your application and creating models in Django. Til then!