Django cheatsheet

12 min. read

Caution! This article is 6 years old. It may be obsolete or show old techniques. It may also still be relevant, and you may find it useful! So it has been marked as deprecated, just in case.

These are my notes from the Try Django and Digging into Django, courses. You may also be interested in my cheatsheet for the Try Python and Flying through Python courses.

"Try Django" - notes

  • Django follows the Model-View-Controller (MVC) pattern. But in Django, Controllers are called Views, and Views are called Templates, so it is called the Model-Template-View (MTV) pattern:
    # MVC        = MTV
    # ---------------------
    # model      = model
    # view       = template
    # controller = view
  • To install Django, first go learn about virtual environments in Python. Then:
    # $ pip install django

Creating projects

In Django there is one PROJECT that contains several APPS. You have to create one project and one app. Imagine we want to start a project called "Treasuregram". To create this project, type:

$ django-admin startproject Treasuregram

To run the project, cd Treasuregram, and type:

$ python runserver

It creates a db.sqlite3 and tells you:

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python migrate' to apply them.

This is because Django comes with an admin panel out of the box, and those migrations are needed for the admin to work.

Create an app

Go to localhost:8000. It tells you to run:

$ python startapp app_name.

This creates a directory app_name at the same level that the project. You can also go to localhost:8000/admin

Views (the controllers)

Their function is to receive a request and send a response. They go in or inside a directory called views. To render templates, you have to import render.

Django uses a URL dispatcher that matches a URL using regex with the corresponding view. The routes of your web-app live in Project/ For example:

r'^index/' # --> r = raw, (string won't be escaped)
r'^$'      # --> Check that the URL has an empty path, $ terminates the regex

# Examples:
r'^home/'  # targets url/home/ and url/home/foo
r'^home/$' # targets url/home/ only

Templates (the views)

Django looks for template files in the templates directory. But you have to add the app in Project/

A context is a dictionary that maps template variable names to objects. The keys of a context are rendered in double brackets called "moustaches".

There are other interesting things you can do in templates, like looping, cicling, etc. The documentation for that with some examples is in the official page.

Static files

This is anything that goes inside a static folder, for example: styles, scripts, images, etc.

Add {% load staticfiles %} in the template to make them available. Then, to load the path to the static file, do:

<link rel="stylesheet" href="{% static 'main.css %}">


Django uses ORM (Object Relational Mapping) to translate Python to SQL statements.

Right after you create or update a model you have to do a migration (same in Rails). This is like version control but for databases.

$ python makemigrations
$ python migrate

We can preview the SQL commands that would be run with:

$ python sqlmigrate main_app 0001

If you run makemigrations and migrate again, it would tell you "nothing to do".

Django shell

Django comes with a special shell that provides extra django commands, for example, to manipulate the database, add/update/remove records, etc.:

$ python shell
> from main_app.models import Treasure

Now we can do queries in our database, for example:

> Treasure.objects.all()

This is equivalent to SELECT * FROM Treasure. The return value is called a Django QuerySet.

There is also the equivalent of WHERE, and you have two methods for that; one that returns a group of records (filter()) and one that returns a single record (get()):

> Treasure.objects.filter(location = 'Orlando, FL')
> Treasure.objects.get(pk = 1)

Here,pk refers to the primary key, which uniquely identifies an object (or a row in a databse table), so the result will return just one object.

We can use the Django shell, to manually introduce data in the database:

> t = Treasure(name="Gold Nugget", value=500.00, material='gold',   location="Curly's Creek, NM", img_url='')
> t = Treasure(name="Fool's Gold", value=0,      material='pyrite', location="Fool's Falls, CO",  img_url='')
> t = Treasure(name="Coffee Can",  value=20.00,  material='tin',    location="Acme, CA",          img_url='')

Defining a def __str__(self): method in the model allows us to see something useful in the console.

The admin panel

Got to http://localhost/admin. You will see a login screen. When you first create a Django app, the admin table is empty. So let's create an admin user:

$ python createsuperuser

You will be able to login now, but the screen will be empty. This is because you have to register your models with the admin for them to show up.

In, we import the models and register them:

from django.contrib import admin
from .models import Treasure

This is all in the Try Django tutorial. It's al lthe basic stuff to allow you to start making very basic Django sites.

You could stop here and go practice what you learnt, or keep reading for more advanced stuff.

"Flying through Python" - notes

Random templating wisdom: there are things called "template tags" that will allow you to add some simple logic to the templates (I am against having any logic in the templates, but this is something that the framework offers you). For example, you can sort a dictionary:

{% for location in locations|dictsort:'name' %} sort by name

To catch an id passed through a url (for example, http://example.dom/user/3), we can use: [0-9]+. This matches any number, then we capture it with () so that it gets passed as a parameter to the method in the view.

One to many relationship

Imagine we want to associate a user with their treasures. One user can own many treasures. But one treasure has only one owner. This is called a "one-to-many" relationship.

In the treasure model, add:

from django.contrib.auth.models import User

and then in the model class definition add:

user = models.ForeignKey(User)

that will tell both tables to use the user id of the User table as a foreign key.

Then migrate. You will get the message "you are trying to add a non-nullable field". Provide a one-off default and type 1 to give all current records in the table a foreign key that points to the first user.


You can have Django tell a transaction to be complete or incomplete:

The last one allows you to do stuff before saving.

User login

There is a built in login function in Django, so if you want to make your own be carefull with naming.

# action="." means post to same page.

This is still WIP, more to come in the future!

The end

This is the end, from here you may want to go back to virtual environments in Python or jump to my Python cheatsheet. I hope they are useful!