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

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

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

python -m pip install --upgrade pip

Then create a requirements.txt file inside myvenvwith 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

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

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

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

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 environ
env = 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

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!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store