Introduction à Django

44
Introduction à Django La plateforme de développement web pour les perfectionnistes avec des livrables. présenté par jeudi 28 février 13

description

Introduction à Django présentée à Confoo 2013.

Transcript of Introduction à Django

Page 1: Introduction à Django

Introduction à DjangoLa plateforme de développement web pour

les perfectionnistes avec des livrables.

présenté par

jeudi 28 février 13

Page 2: Introduction à Django

BENOITDOMINGUE

@bedingue

Copyright Reptiletech 2013jeudi 28 février 13

Page 3: Introduction à Django

jeudi 28 février 13

Page 4: Introduction à Django

jeudi 28 février 13

Page 5: Introduction à Django

jeudi 28 février 13

Page 6: Introduction à Django

jeudi 28 février 13

Page 7: Introduction à Django

jeudi 28 février 13

Page 8: Introduction à Django

jeudi 28 février 13

Page 9: Introduction à Django

22 OCTOBRE 2012 > REPTILETECH CONFIDENTIELLECopyright Reptiletech 2013

C’est quoi Django ? Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.

source : https://www.djangoproject.com/jeudi 28 février 13

Page 10: Introduction à Django

Copyright Reptiletech 2013

Python•Existe depuis 1989•Langague dynamique et oritenté object•Syntaxe simple et élégante•Librarie standard complète

source : http://en.wikipedia.org/wiki/Python_(programming_language)jeudi 28 février 13

Page 11: Introduction à Django

source : httphttp://xkcd.com/353/

import antigravity

jeudi 28 février 13

Page 12: Introduction à Django

Qui utilise Django

Copyright Reptiletech 2013jeudi 28 février 13

Page 13: Introduction à Django

ORM Simple et puissantParce qu’en 2013, on a pas besoin d’écrire du SQL

Console AdministrationPermet de se lier à la base de donnée facilement

Pourquoi choisir Django

Copyright Reptiletech 2013jeudi 28 février 13

Page 14: Introduction à Django

Pourquoi choisir Django

Copyright Reptiletech 2013

Gabarits avec héritageL’héritage dans les templates simplifie le htmlInternationalisation + localisationOutils intégrés pour la traduction et la localisation

jeudi 28 février 13

Page 15: Introduction à Django

Pourquoi choisir Django

Copyright Reptiletech 2013

Design d’URL simpleAucune limitation au niveau de la structure des URLCachePeut s’intégrer facilement avec memcached

jeudi 28 février 13

Page 16: Introduction à Django

Pourquoi choisir Django

Copyright Reptiletech 2013

Robuste, Performant et SécuritaireTrois belles qualités pour une plateforme de développement web!

jeudi 28 février 13

Page 17: Introduction à Django

ORMDites au revoir au SQL!

Copyright Reptiletech 2013jeudi 28 février 13

Page 18: Introduction à Django

ORM

Copyright Reptiletech 2013

Exemple d’un modèle - Blog simpleclass Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField()

class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField()

class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author)

source : https://docs.djangoproject.com/en/dev/topics/db/queries/

jeudi 28 février 13

Page 19: Introduction à Django

ORM

Copyright Reptiletech 2013

Requêtes Simples

all_entries = Entry.objects.all()SELECT * FROM ...;

Entry.objects.get(headline="Man bites dog")SELECT ... WHERE headline = 'Man bites dog';

Entry.objects.get(headline__contains='Lennon')SELECT ... WHERE headline LIKE '%Lennon%';

source : https://docs.djangoproject.com/en/dev/topics/db/queries/

jeudi 28 février 13

Page 20: Introduction à Django

ORM

Copyright Reptiletech 2013

Requêtes - suite

Entry.objects.filter(pub_date__year=2006)

Entry.objects.filter(blog__name__exact='Beatles Blog')

Blog.objects.filter(entry__headline__contains='Lennon')

Blog.objects.filter(entry__authors__name='John')

Blog.objects.filter(entry__authors__name__isnull=True)

source : https://docs.djangoproject.com/en/dev/topics/db/queries/

jeudi 28 février 13

Page 21: Introduction à Django

ORM

Copyright Reptiletech 2013

Instance d’un modèle

entry = Entry.objects.get(id=1)blog = entry.blogentry_authors = entry.authors

blog_entries = blog.entries_set.all()author = Author.objects.get(email="[email protected]")author_entries = author.entry_set.all()

recent_author_entries = author.entry_set.filter(pub_date__year=2006)

source : https://docs.djangoproject.com/en/dev/topics/db/queries/

jeudi 28 février 13

Page 22: Introduction à Django

AdminLe pouvoir le l’introspection

Copyright Reptiletech 2013jeudi 28 février 13

Page 23: Introduction à Django

Admin

Copyright Reptiletech 2013

Console d’administrations simples

from django.contrib import adminfrom myproject.myapp.models import Author

class AuthorAdmin(admin.ModelAdmin): pass

admin.site.register(Author, AuthorAdmin)

source : https://docs.djangoproject.com/en/1.5/ref/contrib/admin/

jeudi 28 février 13

Page 24: Introduction à Django

Admin

Copyright Reptiletech 2013

Console d’administration - options

class UserAdmin(ModelAdmin): list_filter = ('is_staff', 'is_superuser') list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') search_fields = ('first_name', 'last_name', 'email')

source : https://docs.djangoproject.com/en/1.5/ref/contrib/admin/

jeudi 28 février 13

Page 25: Introduction à Django

Admin

Copyright Reptiletech 2013

Console d’administration - options suite

source : https://docs.djangoproject.com/en/1.5/ref/contrib/admin/

• inlines

• fields

• fieldsets

• readonly_fields

• list_editable

• ordering

• form

• etc.

jeudi 28 février 13

Page 26: Introduction à Django

TemplatesL’héritage au service du HTML

ré-utilisable

Copyright Reptiletech 2013jeudi 28 février 13

Page 27: Introduction à Django

Templates

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/templates/

{{ une_variable }}{% un_tag %}

Templates - Syntaxe

jeudi 28 février 13

Page 28: Introduction à Django

Templates - héritage

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/templates/

<!DOCTYPE html><html lang="en"><head> <link rel="stylesheet" href="style.css" /> <title>{% block title %}My amazing site{% endblock %}</title></head><body> <div id="sidebar"> {% block sidebar %} <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div></body></html>

Template de base

jeudi 28 février 13

Page 29: Introduction à Django

Templates - héritage

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/templates/

{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}{% for entry in blog_entries %} <h2>{{ entry.title }}</h2> <p>{{ entry.body }}</p>{% endfor %}{% endblock %}

Template qui profite de l’héritage

jeudi 28 février 13

Page 30: Introduction à Django

Templates

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/templates/

{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}<h1>{{ section.title }}</h1>

{% for story in story_list %}<h2> <a href="{{ story.get_absolute_url }}"> {{ story.headline|upper }} </a></h2><p>{{ story.tease|truncatewords:"100" }}</p>{% endfor %}{% endblock %}

Templates - Tags et filtres

jeudi 28 février 13

Page 31: Introduction à Django

Templates

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/templates/

Templates - Pour aller plus loin...

Ajouter un filtreIl s’agit simplement d’une fonction

Ajouter un tagOn sous classe le tag et on peut faire n’importe quoi

jeudi 28 février 13

Page 32: Introduction à Django

URLSGrâce aux expressions régulières,

tout est possible!

Copyright Reptiletech 2013jeudi 28 février 13

Page 33: Introduction à Django

URLS

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.conf.urls import patterns

urlpatterns = patterns('', (r'^blog/$', 'blog.views.page'), (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),)

# View (in blog/views.py)def page(request, num="1"): # Output the appropriate page of blog entries, according to num.

Exemple simple

jeudi 28 février 13

Page 34: Introduction à Django

URLS

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.conf.urls import patterns

urlpatterns = patterns('', (r'^articles/(\d{4})/$', 'news.views.year_archive'), (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), (r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),)

Autre exemple

jeudi 28 février 13

Page 35: Introduction à Django

URLS

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.conf.urls import patterns

urlpatterns = patterns('', (r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),)

Dans les templates

{% extends "base.html" %}{% block content %} <a href="{% url 'news.views.month_archive' 2013 03 %}"> Lien vers les articles de mars 2013 </a>{% endblock %}

jeudi 28 février 13

Page 36: Introduction à Django

URLS

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.conf.urls import patterns

urlpatterns = patterns('', url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive', name="article_archive"),)

Dans les templates

{% extends "base.html" %}{% block content %} <a href="{% url 'article_archive' 2013 03 %}"> Lien vers les articles de mars 2013 </a>{% endblock %}

jeudi 28 février 13

Page 37: Introduction à Django

URLS

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.conf.urls import patterns

urlpatterns = patterns('', url(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive', name="article_archive"),)

Dans les templates

{% extends "base.html" %}{% block content %} <a href="{% url 'article_archive' month='03' year='2013' %}"> Lien vers les articles de mars 2013 </a>{% endblock %}

jeudi 28 février 13

Page 38: Introduction à Django

ViewsC’est par là que ça se passe!

(dernier morceau du casse tête)

Copyright Reptiletech 2013jeudi 28 février 13

Page 39: Introduction à Django

Views

Copyright Reptiletech 2013

Préparer les données - Faire les requêtes à la BDD - Valider les formulaires - Logique propre à l’applicationRenvoyer une réponse- Rediriger- Renvoyer un document html- etc.

source : https://docs.djangoproject.com/en/1.5/topics/http/views/

Deux responsabilités

jeudi 28 février 13

Page 40: Introduction à Django

Views

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.shortcuts import get_object_or_404, render_to_response

def article_detail(request, slug): article = get_object_or_404(Article, slug=slug) return render_to_response('article/detail.html', {'article': article})

Exemple

jeudi 28 février 13

Page 41: Introduction à Django

Views

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.shortcuts import get_object_or_404, render_to_response

def article_detail(request, slug): article = get_object_or_404(Article, slug=slug) return render_to_response('article/detail.html', {'article': article})

Exemple

{% extends "base.html" %}{% block content %} <a href="{% url 'article_detail' slug='mon-article' %}"> Lien vers mon article </a>{% endblock %}

urlpatterns = patterns('', (r'^articles/(?P<slug>[\w\-]+)/$', 'articles.views.article_detail'),)

jeudi 28 février 13

Page 42: Introduction à Django

Views

Copyright Reptiletech 2013source : https://docs.djangoproject.com/en/1.5/topics/http/urls/

from django.contrib.auth.decorators import login_required

@login_requireddef article_detail(request, slug): article = get_object_or_404(Article, slug=slug) return render_to_response('article/detail.html', {'article': article})

Decorators

from django.views.decorators.cache import cache_page

@cache_page(60 * 15)def article_detail(request): article = get_object_or_404(Article, slug=slug) return render_to_response('article/detail.html', {'article': article})

jeudi 28 février 13

Page 43: Introduction à Django

Démo!

Copyright Reptiletech 2013jeudi 28 février 13

Page 44: Introduction à Django

MERCI!

Copyright Reptiletech 2013jeudi 28 février 13