Home

Awesome

:scroll: Django Cheat Sheet

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 for Django v2.0.

Sections

:snake: Initializing pipenv (optional)

:blue_book: Creating a project

The project directory should look like this:

project/
    manage.py
    project/
        __init__.py
        settings.py
        urls.py
        wsgi.py
SECRET_KEY = os.environ.get('SECRET_KEY')
>>> import secrets
>>> secrets.token_hex()

:page_with_curl: Creating an app

The project directory should now look like this:

project/
    manage.py
    db.sqlite3
    project/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    app/
        migrations/
            __init__.py
        __init__.py
        admin.py
        apps.py
        models.py
        tests.py
        urls.py
        views.py
INSTALLED_APPS = [
	'app',
	# ...
]
$ python manage.py migrate

:tv: Creating a view

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('app/', include('app.urls')),
    path('admin/', admin.site.urls),
]
urlpatterns = [
    path("", include('app.urls')),
]

:art: Creating a template

app/
   templates/
      index.html
   static/
      style.css
      script.js
from django.shortcuts import render

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

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		
		<link rel="stylesheet" href="{% static 'styles.css' %}">
	</head>
</html>
STATIC_URL = '/static/'
STATICFILES_DIRS = [
	os.path.join(BASE_DIR, "static")
]
{% extends 'base.html'%}

{% block content %}

Hello, World!

{% endblock %}
<body>
	{% block content %}{% endblock %}
</body>

:ticket: Creating a model

from django.db import models

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

Note that you don't need to create a primary key, Django automatically adds an IntegerField.

$ python manage.py makemigrations <app_name>
$ python manage.py migrate

Note: including <app_name> is optional.

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()
>>> m = Musician.objects.get(pk=1)
>>> a = m.album_set.get()
class Topping(models.Model):
    # ...
    pass

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.

ForeignKey(SomeModel, unique=True)

:postbox: Creating model objects and queries

from django.db import models

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

    def __str__(self):
        return self.name

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

    def __str__(self):
        return self.name

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
$ python manage.py shell
>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()
>>> b.name = 'The Best Beatles Blog'
>>> b.save()
>>> all_entries = Entry.objects.all()
>>> indexed_entry = Entry.objects.get(pk=1)
>>> find_entry = Entry.objects.filter(name='Beatles Blog')

:man: Using the Admin page

$ python manage.py createsuperuser
from django.contrib import admin
from .models import Author, Book

admin.site.register(Author)
admin.site.register(Book)