2. What is Django?
“Django is a high-level Python Web framework that
encourages rapid development and clean, pragmatic
design.”
www.djangoproject.com
• Created out of the newspaper industry
• Help developers build sites fast
• Encourage Reuse and Lose Coupling
• DRY (don’t repeat yourself)
• Minimal Code
• Opinionated
3. Batteries Included
django.contrib
• Admin Interface for editing data.
• Auth module for user accounts
• Syndication module for generation of RSS
• Static Pages
4. Active Community
• Many Community Contributed Apps
• Pinax
http://pinaxproject.com/
• Django Packages
http://djangopackages.com/
5. Django Projects
• A project is your website.
• Projects contain the configuration information for
your site.
• Create a project:
django-admin.py startproject [PROJECT_NAME]
• Projects contain 3 files:
• settings.py - configuration information for your project
• urls.py - URL routes defined by your project
• manage.py - alias of django-admin.py tuned to your project
6. Django Applications
• Projects are built from Applications
• Apps encapsulate some piece of
functionality
• blog, photo gallery, shopping cart, etc.
• Apps can be reused
• Apps are Python Packages
• manage.py startapp [MY_APP_NAME]
7. Django Application
Components
• Models - Your Data
• Views - Rules for Accessing Data
• Templates - Displays Data
• URL Patterns - Maps URLs to Views
8. Models
• Describes the data in your apps
• Defined in an app’s models.py file
• Map Python Classes to Database Tables
• Provides an API for creating, retrieving,
changing and deleting data
9. Blog Data Definition
CREATE TABLE "blog_category" (
"id" integer NOT NULL PRIMARY KEY,
"name" varchar(50) NOT NULL
);
CREATE TABLE "blog_blogpost" (
"id" integer NOT NULL PRIMARY KEY,
"title" varchar(100) NOT NULL,
"slug" varchar(50) NOT NULL UNIQUE,
"publish_date" datetime NOT NULL,
"is_published" bool NOT NULL,
"content" text NOT NULL,
"category_id" integer NOT NULL REFERENCES "blog_category" ("id")
);
10. Django Hides the SQL
• SQL is not consistent across databases
• Difficult to store in version control
11. Model Example
from django.db import models
from datetime import datetime
class Category(models.Model):
name = models.CharField(max_length=50)
class BlogPost(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
publish_date = models.DateTimeField(default=datetime.now)
is_published = models.BooleanField(default=False)
content = models.TextField(blank=True)
category = models.ForeignKey(Category,
related_name=‘posts’)
12. Creating your database
• manage.py syncdb command creates tables
from models
• Creates all models for any app in your
project’s INSTALLED_APPS setting
14. Views
• Business Logic
• Perform a task and render output
(HTML/JSON/XML)
• Python function that takes an HttpRequest
and returns an HttpResponse
• Defined in an app’s views.py file
15. Hello World View
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello World")
17. Post Detail View
from django.shortcuts import render, get_object_or_404
from blog.models import BlogPost
def blog_post_detail(request, slug):
post = get_object_or_404(BlogPost, slug=slug)
return render( request, "blog/blogpost_detail.html",
{"post":post})
18. URL Routes
• Defines the URLs used in your project
• Maps a URL to a View Function
• Defined using Regular Expressions
• Defined in an app’s urls.py file.
20. Templates
• Describes the Presentation of your data
• Separates Logic from Presentation
• Simple Syntax
• Designer Friendly
• Supports Reuse through inheritance and
inclusion
• Blocks allow child templates to insert
content into parent templates
21. Template Syntax
• Variables: {{variable-name}}
• Tags: Perform logic
{% include “_form.html” %}
• Filters: Operate on data
{{post.publish_date|date:"m/d/Y"}}
23. Template
“latest_posts.html”
{% extends "base.html" %}
{% block title %}Latest Blog Posts -
{% endblock %}
{% block content %}
<h2>Latest Blog Posts</h1>
{% for p in posts %}
<h3><a href="{% url blog_blogpost_detail p.slug %}">{{p.title}}</a></h3>
<p><strong>Published:</strong>
{{p.publish_date|date:"m/d/Y"}}
</p>
<div class="content">
{{p.content|safe}}
</div>
{% endfor %}
{% endblock %}
List of Template Tags and Filters: https://docs.djangoproject.com/en/dev/ref/templates/builtins/
24. The admin
• Not a CMS
• Allows site admins to edit content
• Auto CRUD views for your models
• Easy to customize
• Optional. If you don’t like it you can write
your own
28. The admin
• add django.contrib.admin to
INSTALLED_APPS
• Uncomment admin import, discover, and url
pattern from PROJECTS urls.py
• Create an admin.py file for each app you
want to manage
31. Resources
• Official Django Tutorial
https://docs.djangoproject.com/en/dev/intro/tutorial01/
• Django Documentation
https://docs.djangoproject.com/
• The Django Book
http://www.djangobook.com/
• Practical Django Projects
https://docs.djangoproject.com/
• Pro Django
http://prodjango.com/
32. Thank You
Wade Austin
http://wadeaustin.com
@k_wade_a
Editor's Notes
Ask audience questions.\nWho knows Python?\nWho here has used Django?\nExperience building websites / web development?\nOther webdev frameworks?\n
Framework created in 2005 at a newspaper Lawrence Kansas\nCreated out of a need to develop sites fast on a real-world news cycle\nTasked with creating sites at journalism deadline. Be able to launch sites is hours / days as opposed to weeks / months.\nDjango is Python, if you are learning Django you are learning Python.\n\nWhat is a web-framework? It makes routine development tasks easier by using shortcuts.\nExamples: Database CRUD, form processing, clean urls, etc.\nOpinionated about the right way to do things, makes doing things that way easier \nNot a CMS.\n
\n
\n
Projects are your site\n
Projects/Sites tend to have lots of applications\nApps are pieces of re-use.\nApps should be small, sites are made up of lots of apps\n
\n
Describes the types of data your apps have and what fields/attributes those types have\nModels map one-to-one to DB tables\nDB neutral. Hides SQL (unless you need it) SQLite for development, PostGres for production\nsyncdb installs all models listed in INSTALLED_APPS\n\n
\n
\n
Fields for different data types\nCharField short string\nDateTime, Time, Date fields for date/time information\nTextField for larger text information\nBoolean, Integer, Float for example\nForeignKey, ManyToMany, OneToOne for relationships\n\nwell documented online\n
\n
Filters can be chained.\nQuery is not executed until the result is operated so calling filter multi times is not a penalty.\nFields to Query are escaped to prevent against SQL Injection\n
A python function that accepts an HttpRequest and returns a HttpResponse\n
\n
View is a function (or any callable) accepts a HttpRequest object and returns a HttpResponse object\nQuerying BlogPost to get a list of posts that are marked as published and their publish date is not in the future.\nUses a Django shortcut function called render that takes a response, a template name, and dictionary of objects and returns\na response that renders the given template using the dictionary\n\n
\n
\n
2 URL patters 1 for the latest posts, 1 for post detail\npost detail uses a regex to capture a keyword argument to the view function (slug)\nThe name argument is a unique string to identify a url pattern. Usually named (appname_model_view) to keep from clashes\nUseful so you can reference a URL by its name not hardcode the URL. Decouples the url. allows you to change url and not break stuff\n
Templates can inherit from base template for reuse and include sub templates (i.e. a common form template)\n
\n
Simple HTML layout\nblocks are where inherited templates can generate output\n2 Blocks: title (for page title) & content (for body content)\n
extends the base template\nAdds its base title as just text output\nIterates over each blog posts that was passed in from our view\nPrints out the title, the date formated, and the content|safe\nDjango escapes all HTML output in a template, must mark a field as &#x201C;safe&#x201D; before it is rendered.\n
Admin is not a CMS. Not intended for end uses.\nUseful by site editors/admins to edit data of your models.\nProvides a quick interface for basic site information editing.\nFor many sites it is enough.\nCan be customized.\n
\n
List edit screen. \nsearch at the top, filters on the right\n
\n
\n
Imports Django admin module\nCreates a simple class for the model we want to administer\nSimple things you can do in an admin class. Fields displayed on the list page, fields you can filter by in the admin, fields you can search on.\nMany more customizations listed in docs.\nRegisters that models with the admin class it belongs to\n