Django Cheatsheet

Nick Wurzer

Below will be a list of specific Django features with a short description of how they are used.

Scope

I will not cover two very key topics here which are views and models. I will not cover models because it is relatively rare that updates to models will be needed and if so I think you should read the documentation directly to get a good understanding of models before making major changes. I will not cover views mostly because on the surface there isn’t much to them, but there are quite a few generic views that may require some reading to use. Django documentation is excellent and I highly recommend that you read through parts of it if you haven’t already.

Setup

Let’s pretend we are making a project about nonsense. The models found below have the following characteristics. There is a one-to-many relationship between a SnickerSnacker and a DooDad because a SnickerSnacker may be composed of many DooDads (obviously). The same is true for DooDads and WhirlyGigs. All models have a name field and SnickerSnacker also has a price field.

SnickerSnacker(models.Model):
    name = models.CharField(primary_key=True, max_length=50, db_index=True)
    gizmo = models.CharField(max_length=50)
    price = models.IntegerField(blank=True, null=True)

DooDad(models.Model):
    snicker_snacker = models.ForeignKey(SnickerSnacker, on_delete=Models.CASCADE, related_name='snicker_snackers')
    name = models.CharField(max_length=50, primary_key=True)

WhirlyGig(models.Model):
    doo_dad = models.ForeignKey(DooDad, on_delete=Models.CASCADE)
    name = models.CharField(max_length=50, primary_key=True)

Server-Side Python

I’ll list the functions that I use most often but the full Django QuerySet API can be found here. There is also more tutorial-like documentation for making queries with some more advanced topics as well.

Queries

Get all the SnickerSnackers
SnickerSnacker.objects.all()

Get all SnickerSnackers which have a gizmo ’thingamabob’, except ones with name ‘knick knack’.
SnickerSnacker.objects.filter(gizmo='thingamabob').exclude(name='Knick Knack')

Get all SnickerSnackers whose name ends with ‘Knack’ (case insensitive) ordered by gizmo.
Note: Postgres and SQLite may return different default orderings, so it’s usually a good idea to be explicit about the ordering.
SnickerSnacker.objects.filter(name__iendswith='Knack').order_by(gizmo)
 Other popular field lookups include __startswith, __exact and __contains along with their case insensitive versions __istartswith, __icontains and __iexact.

Get a QuerySet of all SnickerSnacker’s names.
SnickerSnacker.objects.values_list("name", flat=True)

Get the DooDad named ‘gibberish’. get() returns one object or a Models.MultipleObjectsReturned error.
DooDad.objects.get(name='gibberish')

 Just like it is useful to get the SnickerSnacker for a particular DooDad, it is also often useful to get every DooDad that associated with a SnickerSnacker.
 I’ll go over the main points but here is documentation for foreign key relationships.

 Unless the related_name attribute is set to some string in models, the default way to filter for all objects with particular foreign key is to use the object’s
 class name followed by _set.

For example if we have a SnickerSnacker:
snickersnacker = SnickerSnacker.objects.get(name='gobbledegook')

Then we can get all DooDads with that SnickerSnacker as a foreign key with:
snickersnacker.DooDad_set.all()

This is equivalent to:
Doodad.objects.filter(snickersnacker=snickersnacker)

Aggregating

Get the total number of SnickerSnackers.
SnickerSnacker.objects.count()

Get the greatest price for all SnickerSnackers.

from django.db.models import Max
SnickerSnacker.objects.aggregate(Max('price', default=0))

Templates

Django has a reasonable template system, although I think something like Jinja is much more advanced. The thinking behind this is that the vast majority of the logic should be performed in the views. Below, I’ll show the main features of Django’s templates. Here is a link to the template documentation.

Variables

A variable is denoted in a template with two curly braces like {{ a_variable }}. The templates also support a dot syntax for various lookups.

From the Django documentation:

Technically, when the template system encounters a dot, it tries the following lookups, in this order:

  • Dictionary lookup
  • Attribute or method lookup
  • Numeric index lookup

Some dictionary item where key = a_key could be accessed with {{ a_dict.a_key }}.
A model instance or function could be accessed with {{ a_snickersnacker.name }} for example. Functions must not have parameters other than the object itself.
A list item could be accessed using it’s index {{ a_list.1 }}.

Filters

Template filters are different from the Python filter() function. Variables can be followed with a pipe character (|) and then the name of the filter.

Some useful filters are:

Get a slice of a list.
{{ a_list|slice:":4" }}

Add an ’s’ if the variable isn’t equal to 1. apple{{ apple|pluralize }}

Get the length of a string or list.
{{ 'hello'|length }}

If some variable if None then dispaly it as 0.
{{ some_varaible|default_if_none:"0" }}

Tags

Tags use the syntax {% some_tag %} and they perform various operations in a template. I’ll list the ones we use most.

Block tags are used in template inheritance. If one template extends another, then it can override the block’s content. This is useful if you have some default content that you want to display unless another template displays something more specific, or if many templates will implement some part of the page differently, but will always share certain components.

{% block block_name %}
  Some content
{% endblock %}

Single Line comment.
{# Some documentation #}

Multiline comment.

{% comment %}
  Some
  comments
{% endcomment %}

Conditionally display something or execute Django template code.

{% if an_int in some_list %}
  do something
{% elif an_int < 6 and an_int != 3 %}
  do something else
{% else %}
  do the other thing
{% endif %}

Loop through some items in a dictionary.

{% for k,v in some_dict.items %}
{% endfor %}

Some useful variables within a for loop:
forloop.first is true if it’s the first iteration.
forloop.last similarly.
‘forloop.counter0` a zero-indexed counter for the loop.

Custom tags and filters can also be made easily and loaded with {% load python_file_name %}. For more info see the custom tag documentation.

Management Commands

Various management commands are really useful for adminstrative tasks in your project. Some useful ones are as follows.

Start the Server.
python manage.py runserver 0:8001

Add a superuser so that you can log into the Django admin page.
python manage.py createsuperuser then follow the prompts.

Show all migrations and which ones have been applied.
python manage.py showmigrations

After changing a model you can create the migrations files for that change.
python manage.py makemigrations

Migrate database schema for a specific app to the state of a different migration.
python manage.py migrate <application> <migration number>

Delete all the data in the database. Note: this does not delete the tables or change the schema.
python manage.py flush