Django Cheatsheet

Field notes from learning Django

Julia Wu
5 min readDec 30, 2022


Source: RealPython

I’ve always wanted to experiment with Django after trying out Flask a few years ago. After some initial experimentation to build a search tool for solar farms (django backend, react frontend), I think Django is an optimal choice for building an API quickly from data models. It works great with PostgreSQL and database-driven applications.

Below is a cheatsheet I compiled while building out my experimental app — hope it’s helpful, and let me know what’s missing!


Django is a python-based web framework that follows a Model-View-Template pattern, where:

  • Model is the interface to your data. Logical structure behind the application and represented by a DB
  • View is the user interface. Whatever your browser renders via HTML/CSS/JS
  • Template is the file that defines the structure or layout of the user interface

Generally, Django is known to be fast, secure, scalable and comes with “batteries included” (user authentication, content management, etc). It is used by newspaper publishers like Washington Post, The Onion, NYT, and apps such as Firefox, ClubHouse, Instagram, Pinterest, Eventbrite, Doordash, and Robinhood.

The Django REST Framework makes it very easy to build CRUD APIs. It makes serialization easier as it follows Django’s class-based views. Overall, a great toolkit for building RESTful APIs.

Cheatsheet & Snippets

Setup & Installation

create a virtual environment

python3 -m venv <name>

activate the venv

source venv/bin/activate

Install django

pip install django

Create a project

django-admin startproject <name> .

Create an app in the project

django-admin startapp <name>

Remember to add the app to the file under INSTALLED_APPS after you create it

Run the server, migrations, etc

Start the server

python3 runserver

Create a migration

python3 makemigrations

Run a migration

python3 migrate

Note: Always run makemigrations followed by migrate after making modifications to data models

Django admin

The admin console is good for inspecting data, users, apis, etc. Usually at localhost:8000/admin

Need to create a login for the admin console:

python3 createsuperuser

You can customize the admin console by updating the file

Data Models

When you create new models:

  1. define models in
  2. update the serializer in
  3. register them in The file must be updated for new models to show up in the admin console.

An example of one-to-many relationships: A book with many characters

The “child” such as characters in a book, should reference the parent via foreign key:

book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='characters')

When you import models from the same directory, you may have to do from .models import ... rather than from models import ...

See here for field options for data models.

Django REST Framework (DRF)


pip install djangorestframework

Add rest_framework to the INSTALLED_APPS list in

To obtain an auth token, hit http://localhost:8000/auth/ (POST) with username and password parameters for a given user. To set up permissions, add this to


Add this to the view set in authentication_classes = (TokenAuthentication, )

This way, only people with an auth token can see the data.

Registering DRF Views as Endpoints

There are multiple types of views in DRF. The most widely used ones are:

  1. Class-based views that extends APIView class
  2. ModelViewSet
  3. Generic Views which map closely to DB models, built on top of APIViews

More on DRF Views here


class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


Typically handles GET, POST based on the incoming query. For example, to create an Authors view based on the Books table:

class Authors(APIView):
renderer_classes = [JSONRenderer]

# return all the unique authors of books
def get(self, request):
authors = Books.objects.order_by().values('author').distinct()
return Response(states)

In api/, the two Views are registered differently. One through the router, another by the path (because you can’t add generic Views in routers)

from django.urls import path, include
from rest_framework import routers
from .views import BookViewSet, Authors

router = routers.DefaultRouter()
# ModelViewSet
router.register('books', BookViewSet)
urlpatterns = [
path('', include(router.urls))
# APIView
path('authors/', Authors.as_view(), name="authors")


Required to allow a frontend application to query API in django


The default is sqlite. To change to Postgres:

To run this locally, make sure you have postgres installed on your machine, and create a database for your project. Install psycopg2 withpip install psycopg2

Fill in your own database credentials in a .env file (example using django Environ)

Finally, update

import environ
env = environ.Env()

'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env("DB_NAME"),
'USER': env("DB_USER"),
'HOST': env("DB_HOST"),
'PORT': env("DB_PORT")

More detailed instructions on using postgres with django

Of course, remember that your local .env file should not be pushed to production. To point your app to a production DB, just update the environment variables.

Remember to recreate any users with the createuser or createsuperuser command

Productionizing with Heroku

  1. install pip install python-decouple
  2. create a .env file and move SECRET_KEY from over
  3. Install pip install dj-database-url and update DB path in
  4. Install pip install dj-static, update to use Cling
from dj_static import Cling from django.core.wsgi import get_wsgi_application  os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<project>.settings")  application = Cling(get_wsgi_application())

5. Run pip freeze > requirements-dev.txt

6. create requirements.txt for heroku, which includes requirements-dev.txt and others

-r requirements-dev.txt 

7. create a Procfile

web: gunicorn <project>.wsgi --log-file -

8. create runtime.txt and input the latest python version supported by heroku

9. deploy with Heroku after pushing changes, either from the dashboard, cli, or automatic github integration

10. monitor logs with heroku logs --tail -a <project>

Running one-off scripts

Install django-extensions and userunscript

python3 runscript <>

Example workflow to build a REST API with Django

  1. Create a directory for the project
  2. start python venv
  3. install django, djangorestframework
  4. start django project
  5. django-admin startproject for the project
  6. django-admin startapp for the app
  7. start the server with python3 runserver
  8. Run migrations with python migrate
  9. update (if applicable, create a new one for your new app in step 6)
urlpatterns = [
path("api/", include('api.urls')),

10. update to include rest_framework and api (new project) in INSTALLED_APPS

11. create superuser with python3 [](<>) createsuperuser

12. routing: in of your app, do from rest_framework import routers

13. define data models in

14. run python3 makemigrations and migrate. If you run into issues like changes not being detected, run python3 makemigrations <app name>

15. Set up serializers for data models in

16. Create views using the serializers (

17. Register the viewsets in your router (

18. Add custom API methods. For example, define POST calls in

Further Reading



Automate Your Life & Business: Top 20 Python Packages

3 min read

Jun 8

Docker for Data Science Projects: A Beginner-Friendly Introduction

12 min read

Jun 3

How to Create an AI Blog Writing Tool with OpenAI API, GPT-3, and Python

3 min read

Dec 28, 2021

I Built a Streamlit App to Generate Websites in Seconds — Try It!

6 min read

Apr 2

Webapps in Python with Solara — A Streamlit Killer?

8 min read

May 14

5 tools to build full-stack apps in Pure Python

3 min read

Jan 23

Building Web Applications with Django and FastAPI: Combining the Best of Both Worlds

6 min read

Apr 30

Why FastAPI is a Future of Python Web Development

7 min read

Feb 27

Beautiful Visual Charts in Django

5 min read

Oct 13, 2019

Top 10 Django Packages You Should Know

5 min read

Mar 26

Julia Wu

Building something new. Prev. eng at Brex, Apple, MSFT. More at