Saturday, August 20, 2016

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)