Django Cheatsheet

Field notes from learning Django

Source: RealPython


Cheatsheet & Snippets

python3 -m venv <name>
source venv/bin/activate
pip install django
django-admin startproject <name> .
django-admin startapp <name>
python3 runserver
python3 makemigrations
python3 migrate
python3 createsuperuser
book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='characters')
pip install djangorestframework
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
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)
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")
from dj_database_url import parse as dburl

# this replaces the initial default for the local db
default_dburl = 'postgres://localhost/<dbname>'

'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
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())
-r requirements-dev.txt 
web: gunicorn <project>.wsgi --log-file -
python3 runscript <>

Example workflow to build a REST API with Django

urlpatterns = [
path("api/", include('api.urls')),

Further Reading



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