An introduction to Django

Tyler Harms / @harmstyler

"Django is a High-level Python web framework that encourages rapid development and clean, pragmatic design."

https://www.djangoproject.com/
Discus
Instagram
Mozilla
OpenStack
Pinterest
PolitiFact.com
Rdio
The New York Times
The Washington Post
NASA
Lanyrd

monty Python

Guido van Rossum

spam & eggs

Significant White Space 

import this

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
...

Installing Django

$ pip install django

$ django-admin.py startproject sdcc

sdcc
 ├── manage.py
 └── sdcc
      ├── __init__.py
      ├── settings.py
      ├── urls.py
      └── wsgi.py

DJAngo-admin.py

Manage.py

Manage.py

$ manage.py <command> [options]

Syncdb

$ python manage.py syncdb Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

Runserver

$ python manage.py runserver

Validating models...

0 errors found
November 09, 2013 - 13:29:07
Django version 1.5.5, using settings 'sdcc.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
http://localhost:8000

startapp

python manage.py startapp <app_name>
$ python manage.py startapp campspeakers

├── campspeakers
│   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
└── sdcc
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    ├── wsgi.py

Settings.py

MVT?

(mvc)

Model-View-Template

Weird nameing convention, but follows M-V-C design pattern.

Model = Model (ORM)
View = Controller
Template = View

Models

models

from django.db import models

class Speaker(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)

    class Meta:
        ordering = ['last_name']

    def _get_full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    full_name = property(_get_full_name)

    def __unicode__(self):
        return self.full_name

Django Admin

django Admin

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'sdcc.views.home', name='home'),
    # url(r'^sdcc/', include('sdcc.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

django Admin

from django.contrib import adminfrom .models import Speaker admin.site.register(Speaker)

django admin

Activate the Admin App
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)    

Views

Views

Functional Based Views
from django.shortcuts import render
from django.http import Http404
from django import template

from .models import Speaker

def index(request):
    try:
        speaker_list = Speaker.objects.all()
    except Speaker.DoesNotExist:
        raise Http404
    return render(request, 'campspeakers/speaker_list.html',
        {'speaker_list': speaker_list})    

views

Class Based Views
Different  Class Based Views exist for different tasks
from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = "campspeakers/index.html"

Views

Class Based Views cont.
from django.views.generic import ListView

from .models import Speaker

class BookListView(ListView):
    model = Speaker

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(BookListView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['speaker_list'] = Speaker.objects.all()
        return context    

Routes

routes

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'sdcc.views.home', name='home'),
    # url(r'^sdcc/', include('sdcc.foo.urls')),
    url(r'^speakers/', include('campspeakers.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

Routes

from django.conf.urls import patterns, url

from .views import BookListView

import views

urlpatterns = patterns('',
    (r'^list$', BookListView.as_view()),
    url(r'^$', views.index, name='index'),
)    

Templates

templates

{% block content %}{% endblock %}
{{ speaker }}

Tips & Tricks

South

"This is South, intelligent schema and data migrations for ​Django projects"

Replaces syncdb.

 $ python manage.py schemamigration campspeakers --initial
 $ python manage.py migrate campspeakers

directory variables

import os

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.abspath(os.path.join(PROJECT_DIR, '../../'))

Django debug toolbar

Resources

Resources

https://docs.djangoproject.com
http://learnpythonthehardway.org/book/
https://github.com/gregmalcolm/python_koans/

Resources

Thanks!

http://spkr8.com/t/27871