SlideShare a Scribd company logo
Introduction to Django



   Master in Free Software 2012, July 14 2012
     Joaquim Rocha <jrocha@igalia.com>
What is it?
"Django is a highlevel Python Web framework
that encourages rapid development and
clean, pragmatic design."



(from Django's official webpage)
What is it?
Created by Lawrence Journal-World en 2003

Should help journalists meet hard deadlines

Should not stand in the way of journalists

Named after the famous Jazz guitar player Django Reinhardt
The framework
Object-Relational Mapper (ORM)

Automatic admin interface

Elegant URL design

Powerful templating system

i18n
Big community
Django has a big community and an extense list of apps

Search for them in http://github.com, http://code.google.com
or http://djangopackages.com

Other interesting web pages:

Django   Planet:https://www.planetdjango.org
Django   Community:https://www.djangoproject.com/community
Django   Sites: http://www.djangosites.org
Django   People: http://www.djangopeople.org
Production Environment
Nginx + Gunicorn
mod_wsgi
FastCGI
mod_python
...
DB Backend
Officially supported:

PostreSQL
MySQL
SQLite
Oracle
Using Django
Development Environment
Download it and install Django from http://djangoproject.com/download or

Be smart and use Python's VirtualEnv
VirtualEnv
A self-contained virtual environment for Python development

Advantages:
* Does not touch your Python installation
* Keep track of needed modules with a requirements file
* Allows to test several package versions
Install VirtualEnv and Django
Install VirtualEnv:
# apt-get install python-virtualenv

Create a virtual environment:
$ virtualenv my_virtual_env

Use a virtual environment:
$ cd my_virtual_env
$ source bin/activate

Install Django inside your virtual environment:
$ pip install django
Development
Creating a project
$ django-admin.py startproject myproject

myproject/
 manage.py
 myproject/
  __init__.py
  settings.py
  urls.py
  wsgi.py
Running a project
$ ./manage.py runserver

... and open in your browser: localhost:8000
Development
Django projects are composed by apps

apps are the projects' modules
Creating an application
Inside a project, do:
$ python manage.py startapp my_app

my_app/
 __init__.py
 models.py
 tests.py
 views.py
Build the DB
$ python manage.py syncdb
Project configuration
Easy configuration in file settings.py
Development
Django follows the MTV design pattern

Model-Template-View
Models
Models are classes that represent objects
in the database

And you'll never have to touch SQL again!
Models
models.py:


class Post(models.Model):

    title = models.CharField(max_length = 500)
    content = models.TextField()
    date = models.DateTimeField(auto_now = True)
    ...
Views
Views are functions that usually process
models and render HTML

It's where the magic happens!

How to get all posts from the last 5 days and order
them by descending date?
View
views.py:


import datetime
from models import Post

def view_latest_posts(request):
    # Last 5 days
    date = datetime.datetime.now() - datetime.timedelta(5)
    posts = Post.objects.filter(date__gte = date).order_by('-date')
    return render_to_response('posts/show_posts.html',
                              {'posts': posts})
Templates
They will help you not repeating yourself!

And designers won't have to touch code:
base.html:

<html>
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
        {% block content %}{% endblock %}
    </body>
</html>
home.html:

{% extends "base.html" %}
{% block title %}Homepage{% endblock %}
{% block content %}
    <h3>This will be some main content</h3>
    {% for post in posts %}
        <h4>{{ post.title }} on {{ post.date|date:"B d, Y"|upper }}<h4>
        <p>{{ post.content }}</p>
    {% endfor %}
    {% url project.some_app.views.some_view some arguments %}
{% endblock %}
URLs
In Django, URLs are part of the design!

urls.py use regular expressions to map URLs with views
URLs
urls.py:


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

urlpatterns = patterns('Project.some_app.views',
  url(r'^$', 'index'),
  url(r'^posts/(?P<r_id>d+)/$', 'view_latest_posts'),
  url(r'^create/$', 'create'),
  url(r'^view/post/(?P<p_id>d+)/$',
      'view', name = 'view_post'),
)
Class-based Views
Allow to structure views and reuse code.
They are also faster to use, for common tasks like listing
or showing objects:


from django.views.generic import DetailView, ListView

urlpatterns = patterns('Project.posts.views',
 (r'^view/(?P<pk>d+)/$', DetailView.as_view(model=Post)),
 (r'^posts/$', ListView.as_view(model=Post)),


By default they try to use the templates:
post_detail.html and post_list.html
but these can be overriden
Forms
Classes that represent HTML forms

They allow to easily configure the
expected type of inputs, error messages, labels, etc.
Forms
forms.py:


class CreatePost(forms.Form):
    title = forms.CharField(label="Post Title",
                  max_length=500,
                  widget=forms.TextInput(attrs={
                                 'class': 'big_entry'
                                }))
    content = forms.TextField()
    tags = forms.CharField(required=False)
Forms
views.py:


def create_post(request):
    if request.method == 'POST':
        form = CreatePost(request.POST)
        if form.is_valid():
           # Create a new post object with data
           # from form.cleaned_data
           return HttpResponseRedirect('/index/')
    else:
        form = CreatePost()
    return render_to_response('create.html',
                              {'form': form})
Forms
create_post.html:


<form action="/create/" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create"/>
</form>
Forms for Models
Forms that are created automatically for modelos, just like:


from django.forms import models

class PostForm(models.ModelForm):
    class Meta:
        model = Post
Automatic Admin
To enable automatic admin, follow the instructions
in your project's URLs (uncomment the admin URLs)
and uncomment the admin app in settings

Then, to add a model to the admin, create an admin.py
file inside an app, for example, for the Post model:


from django.contrib import admin
from models import Post

admin.site.register(Post)
This gives you automatic login...
... and creation, edition, deletion of objects
Next steps
Django friendly hosts
An extense list can be found at:
http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts

Google AppEngine also makes it easy for Django
projects to be deployed:
http://appengine.google.com/
Help
Django Documentation:
https://docs.djangoproject.com

Cheat sheet:
http://www.revsys.com/django/cheatsheet/

Some books:
The Django Book: http://www.djangobook.com/
Learning Website Development with Django, Packt
Practical Django Projects, Apress
Pro Django, Apress

More Related Content

What's hot

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
Stoyan Stefanov
 
An Overview of Models in Django
An Overview of Models in DjangoAn Overview of Models in Django
An Overview of Models in Django
Michael Auritt
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django FrameworkRicardo Soares
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
Muhammad Afzal Qureshi
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
Igor Sobreira
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
Martin Rehfeld
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
Stijn Van Minnebruggen
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
Iakiv Kramarenko
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
Eyal Vardi
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
WebStackAcademy
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
Mariusz Nowak
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)Nicholas Zakas
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
Arti Parab Academics
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
Arti Parab Academics
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 

What's hot (20)

JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
An Overview of Models in Django
An Overview of Models in DjangoAn Overview of Models in Django
An Overview of Models in Django
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
 
JavaScript Modules Done Right
JavaScript Modules Done RightJavaScript Modules Done Right
JavaScript Modules Done Right
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
FYBSC IT Web Programming Unit III Document Object
FYBSC IT Web Programming Unit III  Document ObjectFYBSC IT Web Programming Unit III  Document Object
FYBSC IT Web Programming Unit III Document Object
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 

Viewers also liked

Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5
Joaquim Rocha
 
Hands On The New Hildon
Hands On The New HildonHands On The New Hildon
Hands On The New Hildon
Joaquim Rocha
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a Django
Joaquim Rocha
 
Adapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleAdapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo Fremantle
Joaquim Rocha
 

Viewers also liked (6)

Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5
 
Hands On The New Hildon
Hands On The New HildonHands On The New Hildon
Hands On The New Hildon
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a Django
 
Ocrfeeder
OcrfeederOcrfeeder
Ocrfeeder
 
Python introduction
Python introductionPython introduction
Python introduction
 
Adapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleAdapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo Fremantle
 

Similar to Introduction to Django

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
Lam Hoang
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
Felipe Queiroz
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
jayarao21
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
MoniaJ
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
David Gibbons
 
DJango
DJangoDJango
DJango
Sunil OS
 
Django crush course
Django crush course Django crush course
Django crush course
Mohammed El Rafie Tarabay
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013
Arjan
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
dtdannen
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
Leonardo Fernandes
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
Tikal Knowledge
 
React django
React djangoReact django
React django
Heber Silva
 

Similar to Introduction to Django (20)

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdf
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 
DJango
DJangoDJango
DJango
 
Django crush course
Django crush course Django crush course
Django crush course
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With DeadlinesJBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
JBUG 11 - Django-The Web Framework For Perfectionists With Deadlines
 
React django
React djangoReact django
React django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 

Recently uploaded

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 

Introduction to Django

  • 1. Introduction to Django Master in Free Software 2012, July 14 2012 Joaquim Rocha <jrocha@igalia.com>
  • 2. What is it? "Django is a highlevel Python Web framework that encourages rapid development and clean, pragmatic design." (from Django's official webpage)
  • 3. What is it? Created by Lawrence Journal-World en 2003 Should help journalists meet hard deadlines Should not stand in the way of journalists Named after the famous Jazz guitar player Django Reinhardt
  • 4. The framework Object-Relational Mapper (ORM) Automatic admin interface Elegant URL design Powerful templating system i18n
  • 5. Big community Django has a big community and an extense list of apps Search for them in http://github.com, http://code.google.com or http://djangopackages.com Other interesting web pages: Django Planet:https://www.planetdjango.org Django Community:https://www.djangoproject.com/community Django Sites: http://www.djangosites.org Django People: http://www.djangopeople.org
  • 6. Production Environment Nginx + Gunicorn mod_wsgi FastCGI mod_python ...
  • 9. Development Environment Download it and install Django from http://djangoproject.com/download or Be smart and use Python's VirtualEnv
  • 10. VirtualEnv A self-contained virtual environment for Python development Advantages: * Does not touch your Python installation * Keep track of needed modules with a requirements file * Allows to test several package versions
  • 11. Install VirtualEnv and Django Install VirtualEnv: # apt-get install python-virtualenv Create a virtual environment: $ virtualenv my_virtual_env Use a virtual environment: $ cd my_virtual_env $ source bin/activate Install Django inside your virtual environment: $ pip install django
  • 13. Creating a project $ django-admin.py startproject myproject myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
  • 14. Running a project $ ./manage.py runserver ... and open in your browser: localhost:8000
  • 15. Development Django projects are composed by apps apps are the projects' modules
  • 16. Creating an application Inside a project, do: $ python manage.py startapp my_app my_app/ __init__.py models.py tests.py views.py
  • 17. Build the DB $ python manage.py syncdb
  • 19. Development Django follows the MTV design pattern Model-Template-View
  • 20. Models Models are classes that represent objects in the database And you'll never have to touch SQL again!
  • 21. Models models.py: class Post(models.Model): title = models.CharField(max_length = 500) content = models.TextField() date = models.DateTimeField(auto_now = True) ...
  • 22. Views Views are functions that usually process models and render HTML It's where the magic happens! How to get all posts from the last 5 days and order them by descending date?
  • 23. View views.py: import datetime from models import Post def view_latest_posts(request): # Last 5 days date = datetime.datetime.now() - datetime.timedelta(5) posts = Post.objects.filter(date__gte = date).order_by('-date') return render_to_response('posts/show_posts.html', {'posts': posts})
  • 24. Templates They will help you not repeating yourself! And designers won't have to touch code:
  • 25. base.html: <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body> </html>
  • 26. home.html: {% extends "base.html" %} {% block title %}Homepage{% endblock %} {% block content %} <h3>This will be some main content</h3> {% for post in posts %} <h4>{{ post.title }} on {{ post.date|date:"B d, Y"|upper }}<h4> <p>{{ post.content }}</p> {% endfor %} {% url project.some_app.views.some_view some arguments %} {% endblock %}
  • 27. URLs In Django, URLs are part of the design! urls.py use regular expressions to map URLs with views
  • 28. URLs urls.py: from django.conf.urls import patterns, include, url urlpatterns = patterns('Project.some_app.views', url(r'^$', 'index'), url(r'^posts/(?P<r_id>d+)/$', 'view_latest_posts'), url(r'^create/$', 'create'), url(r'^view/post/(?P<p_id>d+)/$', 'view', name = 'view_post'), )
  • 29. Class-based Views Allow to structure views and reuse code. They are also faster to use, for common tasks like listing or showing objects: from django.views.generic import DetailView, ListView urlpatterns = patterns('Project.posts.views', (r'^view/(?P<pk>d+)/$', DetailView.as_view(model=Post)), (r'^posts/$', ListView.as_view(model=Post)), By default they try to use the templates: post_detail.html and post_list.html but these can be overriden
  • 30. Forms Classes that represent HTML forms They allow to easily configure the expected type of inputs, error messages, labels, etc.
  • 31. Forms forms.py: class CreatePost(forms.Form): title = forms.CharField(label="Post Title", max_length=500, widget=forms.TextInput(attrs={ 'class': 'big_entry' })) content = forms.TextField() tags = forms.CharField(required=False)
  • 32. Forms views.py: def create_post(request): if request.method == 'POST': form = CreatePost(request.POST) if form.is_valid(): # Create a new post object with data # from form.cleaned_data return HttpResponseRedirect('/index/') else: form = CreatePost() return render_to_response('create.html', {'form': form})
  • 33. Forms create_post.html: <form action="/create/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create"/> </form>
  • 34. Forms for Models Forms that are created automatically for modelos, just like: from django.forms import models class PostForm(models.ModelForm): class Meta: model = Post
  • 35. Automatic Admin To enable automatic admin, follow the instructions in your project's URLs (uncomment the admin URLs) and uncomment the admin app in settings Then, to add a model to the admin, create an admin.py file inside an app, for example, for the Post model: from django.contrib import admin from models import Post admin.site.register(Post)
  • 36. This gives you automatic login...
  • 37. ... and creation, edition, deletion of objects
  • 39. Django friendly hosts An extense list can be found at: http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts Google AppEngine also makes it easy for Django projects to be deployed: http://appengine.google.com/
  • 40. Help Django Documentation: https://docs.djangoproject.com Cheat sheet: http://www.revsys.com/django/cheatsheet/ Some books: The Django Book: http://www.djangobook.com/ Learning Website Development with Django, Packt Practical Django Projects, Apress Pro Django, Apress