Skip to main content

Django cheatsheet @djangoproject

Creating a Django project

django-admin startproject <project_name>

Create an app in a project

python startapp <app_name>

Run the project on a server

python runserver

Apply migrations on your app

python migrate

Import modules in your app

In <project_name>/<app_name>/ :

By default, the following will be in your app folder:
from django.shortcuts import render
# Create your views here.

Add the http module in as shown below:
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
return HttpResponse('<h1>Hello Explorers!</h1>')

Map the view to a url

The default file in the <project_name> folder is as follows.

from django.conf.urls import url
from django.contrib import admin
urlpatterns = [

Add a url to your app in the urlpatterns array. The following example is for adding a url ‘index’.

from django.conf.urls import url
from django.contrib import admin
from <app_name> import views
urlpatterns = [
    # localhost/index
    url(r'^index/', views.index),

Refactoring the Project’s URLs Dispatcher

Replace ‘/index’ with ‘/’:

urlpatterns = [
    # localhost/index
    #url(r'^index/', views.index),
    url(r'^', views.index),

Separate project URL dispatcher and app URL dispatcher


urlpatterns = [


from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.index),


Register your App in Settings

In <ProjectName>/ add your app in ‘INSTALLED_APPS’ section. In the example below, we are adding an an App named ‘main_app’ to
The apps listed after main_app are default apps installed by Django.


Create the template

In the <ProjectName>/<AppName> folder create a ‘templates’ folder and an index.html file like the one below.
<!DOCTYPE html>

In the <ProjectName>/<AppName>/ folder, edit the file to render the index.html file instead of returning an HttpResponse.
from django.shortcuts import render

# Create your views here.
def index(request):
     return render(request, 'index.html')

Get Dynamic data in the template

Passing Dynamic Data to the Template

In the <ProjectName>/<AppName>/ folder, edit the file to create new variables, context (json object) and render the html template with the context.

from django.shortcuts import render

def index(request):
name = 'Gold Nugget'
value = 1000.00
context = {
'treasure_name': name,
'treasure_value': value}
     return render(request, 'index.html', context)

Access the variable in the template from the context

In the <ProjectName>/<AppName>/templates/index.html template file, access and display the context variables using the django template language using the double curly braces.

<!DOCTYPE html>
     <p>{{ treasure_name }}</p>
     <p>{{ treasure_value }}</p>

Multiple dynamic data as list of objects

Create the list of objects as shown below using a class and an array list of objects of that class.

from django.shortcuts import render
def index(request):
     return render(request, 'index.html', {'treasures': treasures})

class Treasure:
     def __init__(self, name, value, material, location):
  = name
           self.value = value
           self.material = material
           self.location = location
treasures = {
     Treasure('Gold Nugget', 500.00, 'gold', "Curly's Creek, CA")
     Treasure("Fool's Gold", 0, 'pyrite', "Fool's Falls, CO")
     Treasure('Coffee Can', 20.00, 'tin', 'Acme, CA')

Displaying an array list using the html template

Edit the index.html template to display the array list values.

<!DOCTYPE html>
     <p>{{ treasure_name }}</p>
     <p>{{ treasure_value }}</p>
           {% for treasure in treasures %}
                <p>{{ }}</p>
                <p>{{ treasure.value }}</p>
           {% endfor %}

Add a Django conditional

Add a conditional logic like the following example if required.

           {% for treasure in treasures %}
                <p>{{ }}</p>
                {% if treasure.value > 0 %}
                      <p>{{ treasure.value }}</p>
                {% else %}
                {% endif %}
           {% endfor %}

Styling templates

Django looks for stylesheets in a folder named static. Create a ‘static’ folder in <ProjectName>/<AppName> folder and add a style.css file.

In the html template, add the following Django template language line at the top of the file.
{% load staticfiles %}

Link to the style sheet by adding the following href to the link tag.
<link rel=”stylesheet” type=”text/css” href=”{% static ‘style.css’ %}”/>

Create an images directory in <ProjectName>/<AppName>/<static> folder. Add static images in this folder and use them in the html template.
<nav class="navbar navbar-default navbar-static-top text-center">
<a href="/"><img src="{% static ‘images/logo.png’ %}" alt="TreasureGram"></a>


A model is a mapping to a database table. It is about how we want to store data and retrieve data from the database.

Create a model

In <ProjectName>/<AppName>/ create a model like the one below.

from django.db import models
class Treasure(modesl.Model):
          name = models.CharField(max_length=100)
          value = models.DecimalField(max_digits=10, decimal_places=2)
          material = models.CharField(max_length=100)
          location = models.CharField(max_length=100)
          img_url = models.CharField(max_length=100)


Display the data from the model in the view

Import the Model into of the <AppName> located in <ProjectName>/<AppName>.
from .models import <ModelName>

Create an object array of the Model and pass the object array as a parameter to the template in the index definition of the view.

def index(request):
     treasures = <ModelName>.objects.all()
     return render(request, 'index.html', {'treasures': treasures})

Model Field Types


Django ORM

The Django ORM translates python code to SQL commands.


A Migration is a step that needs to be performed whenever the model is created or updated. This allows the ORM to perform translations correctly.

Make a migration file

python makemigrations

Preview the SQL in the migration

python sqlmigrate <AppName> 0001

Apply the migration to the database

python migrate

Check if migrations need to be applied

Execute either the makemigrations or the migrate commands. If there are no migrations to be applied, the output of the commands will state that clearly.

Django interactive shell

Execute the following command to open the Django shell.

python shell

To play with App objects

Import the model from the app in the shell.

from <AppName>.models import <ModelName>

Execute one or more queries

Equivalent SQL
Display all objects in the model.
SELECT * FROM <ModelName>
<ModelName>.objects.filter(location = ‘Orlando, FL’)
Display all objects in the model where location is ‘Orlando, FL’
SELECT * FROM <ModelName> WHERE location = ‘Orlando, FL’
<ModelName>.objects.get(pk = 1)
Display the object where the value of the primary key is 1
SELECT * FROM <ModelName> WHERE <PrimaryKey> = 1

Create an object in shell

t = <ModelName>(name=’coffee’, value=’2.00’)

Define and display a description for a Model

In add the following to the class.

def __str__(self):

Now, whenever the object is queried in the shell, the output will display the actual value of the object.

Built-in Django Admin

The admin site is accessible from http://<hostname>:8000/admin.

Create super user

To use the admin site, a super user needs to be created. Execute the following command, enter your username, email and password when prompted.

python createsuperuser

By default, the groups and users are visible on the site, but not the models. The models need to be registered by the admin for them to show up on the site.

Register models with the admin

Register the model in <ProjectName>/<AppName>/ to display the model on the admin site.

from django.contrib import admin
# Import the model
from .models import Treasure

# Register your models here.

Popular posts from this blog

A @trello board to get kids excited

My 8 year old just started his summer break. He did so well in school and I am proud of him. He skipped second grade, got into the gold honor roll in every quarter and got a medal for doing that. Last night, I promised to install a new app for him on his iPad mini. I installed Trello and created a board for him while he watched. I showed him how to create cards, add labels to them and move them from To Do, to Doing to Done. I had him create some cards and label them. He could not stop creating cards. I could not convince him to go to bed after that. He created cards for everything he wants to do in the summer and he is not done with creating cards. He even created a card to email a screenshot of his Trello board to his teacher.

Later last night, he was still awake in bed when I checked on him. He told me that he wanted to add three more labels - Math, Science and One-on-One. He wanted a label titled 'One-on-one' for tasks that he wants to do with me and he wants one-on-one att…

A @trello board to get kids excited - continued

This is a continuation of the previous post titled - A trello board to get kids excited. At the time of writing this post, the previous post had 198 page views. I wish people commented. I did get some positive feedback on Twitter. The Trello twitter account re-tweeted my tweet and also sent out a second tweet advertising the page. Thank you very much. I hope a lot of parents and kids benefited and had fun as a result.

Trello people: Idea - How about a 'Trello Kiddo'? Perhaps you could offer that to schools that give iPads for each kid to take home with them. Get them when they are young.

When a kid does something religiously, regularly and feels great about it and can't wait to tell everyone about it, you know you've done well as a parent. We realized that we needed a separate column to keep track of 'Special accomplishments'. Positive reinforcement that you can see with your eyes!

Some parents feel like they haven't done enough for their kids, particularly…

#Git starter cheat sheet

Initialize a local repo Run the following command in the folder where you would like to initialize a git repo.
git init
Get status It is a good practice to frequently run check on status during development. The following command points out the changes between the previous commit and current state of the folder.
git status
Add content To add an untracked file named ‘text.txt’ to the staging area, execute the following command.
git add text.txt
Syntax: git add <filename>
Commit changes To commit changes made to the folder, execute the following command. The message will be used as a commit message to associate this check-in with the message.
git commit –m “Add text.txt to the code base.”
Syntax: git commit –m “<Commit message>”
Add using wild card To add multiple files using a wild card character, execute the following command.
git add ‘*.txt’
Syntax: git add ‘<wildcard_character+string>’
Check history Review commit history using the following command.
git log
Add Remote re…