Introduction au framework Django Création d'une page perso · Django est un framework de...

28
Présentation Création d’une page perso Introduction au framework Django Création d’une page perso Myriam BEGEL Cachan Réseau à Normale Sup’ Mardi 13 décembre 2016 Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 1 / 28

Transcript of Introduction au framework Django Création d'une page perso · Django est un framework de...

Page 1: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Introduction au framework DjangoCréation d’une page perso

Myriam BEGEL

Cachan Réseau à Normale Sup’

Mardi 13 décembre 2016

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 1 / 28

Page 2: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

1 Présentation

2 Création d’une page persoCréer un projetCréation d’un modèleDécouverte de l’interface d’administrationUtiliser un gabaritFormulaire de contactTester son code

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 2 / 28

Page 3: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Plan

1 Présentation

2 Création d’une page persoCréer un projetCréation d’un modèleDécouverte de l’interface d’administrationUtiliser un gabaritFormulaire de contactTester son code

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 3 / 28

Page 4: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Django

Django est un framework de développement web en Python.

The web framework for perfectionists with deadlines.

La documentation est parfaite, disponible pour 5 versions et en 8langues.1

1DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 4 / 28

Page 5: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Modèle MVC

Architecture Modèle - Vue - Contrôleur : classique

Modèle : représente une information, un objet généralementenregistré dans la base de donées

Vue : s’occupe de la visualisation des données, d’actions del’utilisateur comme la soumission de formulaire

Contrôleur : s’occupe des évènements de l’utilisateur, communiqueavec les modèles et transmet les données à la vue

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 5 / 28

Page 6: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Modèle MVC

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 6 / 28

Page 7: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Modèle MVT

Architecture Modèle - Vue - Template : DjangoS’occupe lui-même du Contrôleur

Modèle : représente une information, un objet généralementenregistré dans la base de donées

Vue : s’occupe de la visualisation des données, d’actions del’utilisateur comme la soumission de formulaire

Gabarit (=template) : fichier HTML avec des extensions : boucle for,conditionnelle if, variables ...

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 7 / 28

Page 8: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Modèle MVT

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 8 / 28

Page 9: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Modèle MVT

1 L’utilisateur envoie une requête2 Django appelle la Vue correspondant à l’URL3 La Vue récupère les données, le gabarit4 et génère un rendu HTML pour l’utilisateur

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 9 / 28

Page 10: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Plan

1 Présentation

2 Création d’une page persoCréer un projetCréation d’un modèleDécouverte de l’interface d’administrationUtiliser un gabaritFormulaire de contactTester son code

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 10 / 28

Page 11: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Créer un projet

Démarrer un projet

Projet Git : https://gitlab.crans.org/begel/persodjango-admin startproject perso

perso/manage.pyperso/

__ init__ .pysettings.pyurls.pywsgi.py

./manage.py runserver

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 11 / 28

Page 12: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Créer un projet

Première application

django-admin startapp perso_appperso/

manage.pyperso/perso_app/

__init__ .pyadmin.pyapps.pymodels.pytests.pyviews.py

Ajout de perso_app dans les INSTALLED_APPS de settings.py

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 12 / 28

Page 13: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Créer un projet

Afficher un fichier HTML

Récupérer le gabarit et la feuille de style fournie.

Dans perso/urls.py, inclure les routes de perso_app/urls.py

Ecrire une route dans perso_app/urls.py et la vue correspondante.

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 13 / 28

Page 14: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Création d’un modèle

Premier modèle : Publication

Un modèle est une classe python qui représentera un objet dans labase de données.Les modèles étendent la classe models.ModelLes champs de l’objet que l’on veut enregistrer sont des extensions demodels.Field. Il y en a pour tous les goûts.2

2DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 14 / 28

Page 15: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Création d’un modèle

Premier modèle : Publication

1 class Publication(models.Model):2 titre = models.CharField(max_length = 200)3 auteurs = models.CharField(max_length = 200)4 date = models.DateField()5 editeur = models.CharField(max_length = 200, blank =

True)6 description = models.TextField()7

8 def __str__(self):9 return self.titre

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 15 / 28

Page 16: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Création d’un modèle

Premier modèle : Publication

Pour créer la table dans la base de données :

./manage.py makemigrations

./manage.py migrate

A faire à chaque fois que l’on crée/change un modèle.Pour "jouer" avec le modèle, on peut ouvrir un shell :./manage.py shell

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 16 / 28

Page 17: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Découverte de l’interface d’administration

Administration des modèles

Django fournit une interface d’administration pour gérer les modèles.3

On peut créer, modifier, supprimer des instances.On peut aussi personnaliser cette interface, graphiquement mais aussiau niveau des fonctionalités.

127.0.0.1:8000/admin

3DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 17 / 28

Page 18: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Découverte de l’interface d’administration

Création d’un super-utilisateur

Pour accéder à l’interface d’admin, il faut des comptes.On peut gérer cela dans l’interface mais il nous faut un premierutilisateur.

./manage.py createsuperuser

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 18 / 28

Page 19: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Découverte de l’interface d’administration

Administrer Publication

Dans admin.py, enregistrer le modèle Publication.

admin.site.register(Publication)

C’est ici qu’on enregistrera de nouvelles publications.

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 19 / 28

Page 20: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Utiliser un gabarit

Un gabarit

Un gabarit est un fichier HTML avec des extensions.4

1 {% for publication in publications %}2 {{ publication }}3 {% endfor %}4

5 {% if publication.editeur %}6 {% else %}7 {% endif %}8

9 <a href="{% url ’accueil’%}"> Accueil </a>

4DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 20 / 28

Page 21: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Utiliser un gabarit

Gabarit pour les publications

A vos claviers !

Ecrire un gabarit, une vue et une règle de routage pour afficher la listedes publications.

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 21 / 28

Page 22: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Utiliser un gabarit

Factoriser/diviser les gabarits

Généralement, dans un site web, il y a une en-tête, un pied de page,un menu communs à toute les pages.

On ne recopie pas le HTML complet !

Création de base.html : un HTML à trous.

1 {% block body %}{% endblock %}

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 22 / 28

Page 23: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Utiliser un gabarit

Factoriser/diviser les gabarits

On étend le gabarit de base et on remplit les trous.

1 {% extends ’perso_app/base.html’ %}2 {% block body %}3 {# Mettre ici le code HTML #}4 {% endblock %}

On peut aussi inclure un gabarit avec la balise include.

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 23 / 28

Page 24: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Formulaire de contact

Un modèle et un formulaire

On peut décrire un formulaire par une classe avec des champsétendant forms.Form dans forms.pyComme pour les modèles, il y une flopée de forms.FieldOn peut aussi créer automatiquement un formulaire à partir d’unmodèle.

1 class ContactForm(ModelForm):2 class Meta:3 model = Contact4 fields = [’nom’, ’mail’, ’raison’, ’message’]

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 24 / 28

Page 25: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Formulaire de contact

Formulaire de contact

Ecrire le modèle correspondantOn pensera à actualiser urls.py, views.py et admin.py (et base.html)Les gabarits savent générer automatiquement le HTML pour unformulaire.

1 class ContactForm(ModelForm):2 class Meta:3 model = Contact4 fields = [’nom’, ’mail’, ’raison’, ’message’]

Attention à ne pas oublier la protection CSRF5

5DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 25 / 28

Page 26: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Formulaire de contact

Traiter l’envoi d’un formulaire

Nouvelle règle de routage - nouvelle vueOn récupère les données et on enregiste le nouveau message.

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 26 / 28

Page 27: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Tester son code

Les tests c’est le bien

Pourquoi écrire des tests ?6

I Gagner du tempsI Vérifier plus rigoureusement, plus rapidementI Gagner la confiance des autresI Prévenir la casse

Que tester ? Les méthodes des modèles et les vues.Ecrire les tests le plus tôt possible, parfois avant même d’écrire lesfonctions.

6DocMyriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 27 / 28

Page 28: Introduction au framework Django Création d'une page perso · Django est un framework de développement web en Python. The web framework for perfectionists with deadlines. La documentation

Présentation Création d’une page perso

Tester son code

Ecrire un test pour Publication

On ajoute une méthode recent au modèle Publication et on la testedans tests.pyPour lancer les tests : ./manage.py test perso_ appDjango lancera les fonctions commençant par ’test’ dans les classesétendant ’TestCase’

Myriam BEGEL (Cr@ns) Introduction au framework Django Création d’une page perso 13/12/2016 28 / 28