nutcroft

Django Project Initialisation Process

When I start a new Django project I can never remember what are the steps to arrive at a functional boilerplate with one Django app, the simplest view to get started, and all dependencies set.

This is a documentation of this process.

Preparation

We assume our project’s name is earth.

We assume we have these installed:

  • bash
  • git
  • python3

Setup project

mkdir earth && cd earth
git init
python3 -m venv venv
source venv/bin/activate

Create requirements.in

cat << EOF > requirements.in
django
EOF

Create requirements_dev.txt

cat << EOF > requirements_dev.txt
pip-tools
ipdb
ipython
isort
flake8
black
coverage
EOF

Create Makefile

cat << EOF > Makefile
.PHONY: format lint cov

lint:
   flake8 --exclude=.git/,venv/ --ignore=E203,E501,W503
   isort --check-only --profile black .
   black --check --exclude '/(\.git|venv)/' .

format:
   black --exclude '/(\.git|venv)/' .
   isort --profile black .

cov:
   coverage run --source='.' --omit 'venv/*' manage.py test
   coverage report -m
EOF

Setup dependencies

pip install -r requirements_dev.txt
pip install --upgrade pip
pip-compile
pip install -r requirements.txt

Start django project

django-admin startproject earth .
django-admin startapp main

Reformat based on black

make format

Create .gitignore

cat << EOF > .gitignore
*.pyc
venv/
EOF

Initial commit

git add .
git commit -m "init django project"

Create main/views.py

cat << EOF > main/views.py
from django.http import HttpResponse


def index(request):
    return HttpResponse("ok")
EOF

Create main/urls.py

cat << EOF > main/urls.py
from django.urls import path

from main import views

urlpatterns = [
    path("", views.index, name="index"),
]
EOF

Edit earth/urls.py

Add the include import:

from django.urls import path, include

And the index path to include all main app urls:

path("", include("main.urls")),

Edit earth/settings.py

import os
SECRET_KEY = os.environ.get("SECRET_KEY", "nonrandom_secret")
DEBUG = True if os.environ.get("NODEBUG") is None else False
ALLOWED_HOSTS = [
    "localhost",
    "127.0.0.1",
]
INSTALLED_APPS = [
    "main.apps.MainConfig",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static")

Migrate and run

python manage.py migrate
python manage.py runserver
← Previous
Tech Makers Webring
Next →