Setup a Django Project

A cheat-sheet for creating web apps with the Django framework using the Python language. Most of the summaries and examples are based on the official documentation.

💡 Always use a Python Virtual Environment and Django Settings Best Practices.

Install Django

pip install django

Creating a Project

  • Navigate to main folder with $ cd <folder>
  • Create project with
django-admin startproject <project_name>

The project directory should look like this:


Run the development server with $ python runserver within the project directory

Creating an App

  • Navigate to the outer project folder $ cd <outer_project_folder>
  • Create app with:
python startapp <app_name>
  • Inside the app folder, create a file called

The project directory should now look like this:


To include this app in your project, add your app to the project's file by adding its name to the INSTALLED_APPS list:

	# ...

Alternatively follow Django Settings Best Practices for complex projects.

To migrate changes over:

$ python migrate

Creating a view

Within the app directory, open and add the following:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")

Still within the app directory, open (or create)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),

Now within the project directory, edit to include the following

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('app/', include('app.urls')),
  • Remember: there may be multiple files named
  • The file within app directories are organized by the found in the project folder.
  • Change app in app.urls with the name of your Django application.

Creating a Template

Within the app directory, create HTML, CSS, and JavaScript files in the following locations:


To add a template to views, open within the app directory and include the following:

from django.shortcuts import render

def index(request):
    return render(request,'index.html')

To include context to the template:

def index(request):
	context = {"context_variable": context_variable}
    return render(request,'index.html', context)

Within the HTML file, you can reference static files by adding the following:

{% load static %}

<!DOCTYPE html>
<html lang="en">
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="{% static 'styles.css' %}">
		{% block content %}{% endblock %}

To make sure to include the following in your

STATIC_URL = 'static/'
	os.path.join(BASE_DIR, "static")

To add an extends:

{% extends 'base.html'%}

{% block content %}

Hello, World!

{% endblock %}

Creating a Model

Within the app's file, an example of a simple model can be added with the following:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

To perform changes in your models, use the following commands in your shell:

$ python makemigrations <app_name>
$ python migrate

Note: including <app_name> is optional.

A one-to-many relationship can be made with a ForeignKey:

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()

In this example, to query for the set of albums of a musician:

>>> m = Musician.objects.get(pk=1)
>>> a = m.album_set.get()

A many-to-many relationship can be made with a ManyToManyField:

class Topping(models.Model):
    # ...

class Pizza(models.Model):
    # ...
    toppings = models.ManyToManyField(Topping)

Note that the ManyToManyField is only defined in one model. It doesn't matter which model has the field, but if in doubt, it should be in the model that will be interacted with in a form.

Although Django provides a OneToOneField relation, a one-to-one relationship can also be defined by adding the kwarg of unique = True to a model's ForeignKey:

ForeignKey(SomeModel, unique=True)

For more detail, the official documentation for database models provides a lot of useful information and examples.

Creating Model Objects and Queries

Example file:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

To create an object within the shell:

$ python shell
>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')

To save a change in an object:

>>> = 'The Best Beatles Blog'

To retrieve objects:

>>> all_entries = Entry.objects.all()
>>> indexed_entry = Entry.objects.get(pk=1)
>>> find_entry = Entry.objects.filter(name='Beatles Blog')

Using the Admin Page

To create a superuser:

$ python createsuperuser

To add a model to the Admin page include the following in

from django.contrib import admin
from .models import Author, Book