Skip to main content

Django cheatsheet @djangoproject

Creating a Django project


django-admin startproject <project_name>

Create an app in a project


python manage.py startapp <app_name>

Run the project on a server


python manage.py runserver

Apply migrations on your app


python manage.py migrate

Import modules in your app


In <project_name>/<app_name>/views.py :

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

Add the http module in views.py 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 urls.py file in the <project_name> folder is as follows.

from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

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 = [
    url(r'^admin/', admin.site.urls),
    # localhost/index
    url(r'^index/', views.index),
]




Refactoring the Project’s URLs Dispatcher


Replace ‘/index’ with ‘/’:

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

Separate project URL dispatcher and app URL dispatcher


Project urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',
    include('main_app.urls')),
]

App urls.py


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




Templates


Register your App in Settings


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

INSTALLED_APPS = [
    'main_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Create the template


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

In the <ProjectName>/<AppName>/ folder, edit the views.py 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 views.py 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>
<html>
<head>
     <title>MainApp</title>
</head>
<body>
     <h1>MainApp</h1>
     <p>{{ treasure_name }}</p>
     <p>{{ treasure_value }}</p>
</body>
</html>



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):
           self.name = 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>
<html>
<head>
     <title>MainApp</title>
</head>
<body>
     <h1>MainApaap</h1>
     <p>{{ treasure_name }}</p>
     <p>{{ treasure_value }}</p>
           {% for treasure in treasures %}
                <p>{{ treasure.name }}</p>
                <p>{{ treasure.value }}</p>
           {% endfor %}
</body>
</html>

Add a Django conditional


Add a conditional logic like the following example if required.

           {% for treasure in treasures %}
                <p>{{ treasure.name }}</p>
                {% if treasure.value > 0 %}
                      <p>{{ treasure.value }}</p>
                {% else %}
                      <p>Unknown</p>
                {% 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>
</nav>

Models

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>/models.py 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 views.py 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
Python
SQL
models.CharField()
string
VARCHAR
models.IntegerField()
int
INTEGER
models.FloatField()
float
FLOAT


Django ORM


The Django ORM translates python code to SQL commands.

Migrations


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 manage.py makemigrations

Preview the SQL in the migration


python manage.py sqlmigrate <AppName> 0001

Apply the migration to the database


python manage.py 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 manage.py 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


QuerySet
Function
Equivalent SQL
<ModelName>.objects.all()
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’)
t.save()

Define and display a description for a Model


In models.py add the following to the class.

def __str__(self):
          return self.name

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 manage.py 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>/admin.py to display the model on the admin site.

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

# Register your models here.
admin.site.register(Treasure)



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 at

Create #VirtualPrivateCloud, NAT Instance and NAT Gateways on @AWSCloud

Create a Virtual Private Cloud, NAT instance and the new NAT Gatweay ... and making it all work. This is a YouTube playlist of three videos.

Cheat sheet to create a #VPC and Subnets on @AWSCloud

One of the critical things to remember for working with a AWS VPC is creating and using it. I had hard time remembering how to do it, so, I wrote down a cheat sheet for myself.  If anyone wants to follow along, just navigate to the VPC page on the AWS Console and start with 'Create VPC' button. Please note that this may cost some dollars if you are not on the free tier. If you are on the free tier and make mistakes, it may cost some dollars. In the steps below, we will be creating the following on a new VPC: An internet gateway One public subnet with routes for accessibility from the internet One private subnet without any routes One EC2 web server with Apache installed in it and serving a sample html page - using the public subnet. One EC2 server with the private subnet and security group that allows access to resources running on the public subnet only.  Create VPC Name tag: myVPC CIDR Block: 10.0.0.0/16 Tenancy: default (Must have default. Otherwise, it