SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

An Overview of Models in Django
An Overview of Models in DjangoAn Overview of Models in Django
An Overview of Models in DjangoMichael 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
 
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 prazosIgor Sobreira
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 
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 injectionEyal 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 RightMariusz 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 JavascriptArti Parab Academics
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
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 ObjectArti Parab Academics
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 

La actualidad más candente (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
 

Destacado

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 5Joaquim Rocha
 
Hands On The New Hildon
Hands On The New HildonHands On The New Hildon
Hands On The New HildonJoaquim Rocha
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a DjangoJoaquim Rocha
 
Adapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleAdapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleJoaquim Rocha
 

Destacado (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 a Introduction to Django

Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheetLam Hoang
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath 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
 
CCCDjango2010.pdf
CCCDjango2010.pdfCCCDjango2010.pdf
CCCDjango2010.pdfjayarao21
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting startedMoniaJ
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web FrameworkDavid Gibbons
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Arjan
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talkdtdannen
 
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 CesLeonardo 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 DeadlinesTikal Knowledge
 

Similar a 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
 

Último

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

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