= Django : Architecture d'un projet, Backend (admin) = <> ---- == INTRODUCTION == * Objectifs * connaître l'architecture d'un projet : principaux fichiers * gérer les données dans le '''backend''' (admin) * Documentation * doc : bonne version de django * officielle : https://docs.djangoproject.com/en/1.4/ * français : http://docs.django-fr.org/ * tutoriel * Part 1 : créer un projet, créer une app, jouer avec ORM (API) '''couvert ici sauf ORM''' * Part 2 : backend (admin) '''couvert ici''' * Part 3 : frontend ''pas couvert ici, (voir atelier [[Ateliers/Django/Frontend|Frontend]])'' * Part 4 : forms et vues génériques ''pas couvert ici'' * Environnement technique * Python >= 2.5 * Django 1.1.1 ou 1.4 * South 0.6 ou 0.7.4 (optionnel, recommandé) * Vérification des versions : {{{ >>> import django >>> django.get_version() '1.4' >>> import south >>> south.__version__ '0.7.4.' }}} * Django : version recommandée à l'AUF * la version qui vient avec debian sur les serveurs de production * sauf si vous êtes prêt à assurer une maintenance manuelle de Django ---- == PARTIE 1 : DÉVELOPPEMENT WEB AVEC DJANGO : ARCHITECTURE D'UN PROJET == === Développement web === * schéma : le [[http://montrealpython.org/r/attachments/13/web-development.jpg|développement web]] * rôle d'un framework web : aider à construire réponse à une requête * environnements * développement (DEV) * déploiement (PROD, TEST) === Django === Pourquoi Django vs autre framework (ex.: CherryPy, Pyramid, web2py) * tout-en-un * admin : meilleur vendeur ;) * docs * communauté : utilisation répandue Principaux fichiers * urls.py * views.py * models.py * templates (HTML) * admin.py ---- == PARTIE 2 : PROJET ET APPLICATIONS == === Projet : définition du besoin === La Direction de l'AUF souhaite pouvoir créer une cartographie des établissements membres de l'AUF. (Un projet de cette nature existe réellement, il s'agit ici d'une simplification pour travailler sur un projet vraisemblable.) On veut gérer : * quels professeurs sont dans quels établissements * quelles formations donnent nos établissements membres * quels laboratoires de recherche sont dans nos établissements membres === Projet : modélisation === * Personne * Etablissement * Formation * Laboratoire === Création du projet === Le projet se nomme "Cartographie des membres". {{{ django-admin.py startproject carto cd carto }}} Django 1.1.1 {{{ django-admin startproject carto cd carto }}} * survol des fichiers générés {{{ python manage.py runserver }}} * settings.py Django 1.4 {{{ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'carto.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } }}} Django 1.1.1 {{{ DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'carto.db' # Or path to database file if using sqlite3. }}} === Création d'une application === {{{ python manage.py startapp annuaire }}} * survol fichiers * annuaire/models.py * documentation : * https://docs.djangoproject.com/en/1.4/topics/db/models/ * https://docs.djangoproject.com/en/1.4/ref/models/fields/ * yeah! on code! * Etablissement.nom * Personne.nom {{{ from django.db import models class Etablissement(models.Model): pass # coder les champs ici class Personne(models.Model): pass # coder les champs ici }}} * settings.py {{{ INSTALLED_APPS = ( # ... 'annuaire', ) }}} === South === * settings.py {{{ INSTALLED_APPS = ( # ... 'south', ) }}} * créer une migration pour une nouvelle application {{{ python manage.py schemamigration annuaire --initial }}} South 0.6 {{{ python manage.py startmigration annuaire nom_migration --initial }}} * ''créer une migration pour un application existante ('''pas le cas ici''')'' {{{ python manage.py schemamigration annuaire --auto }}} South 0.6 {{{ python manage.py startmigration annuaire nom_migration --auto }}} * créer les tables de south {{{ python manage.py syncdb }}} * appliquer les migrations {{{ python manage.py migrate annuaire }}} ''Si vous n'avez pas South d'installé, créez directement les tables sans suivre leur évolution:'' * création des tables dans DB correspondant à nos modèles {{{ python manage.py syncdb }}} == PARTIE 3 : BACKEND (ADMIN) == === Backend : gérer les données dans l'admin === * urls.py ''activer admin : décommenter'' {{{ # ... from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # ... url(r'^admin/', include(admin.site.urls)), ) }}} * http://127.0.0.1:8000/ * settings.py {{{ INSTALLED_APPS = ( # ... 'django.contrib.admin', # ... ) }}} * créer les tables de l'admin {{{ python manage.py syncdb }}} * http://127.0.0.1:8000/admin/ * annuaire/admin.py ''enregistrer modèles voir tutoriel Part 2'' * https://docs.djangoproject.com/en/1.4/intro/tutorial02/ {{{ from django.contrib import admin from annuaire.models import * admin.site.register(Etablissement) admin.site.register(Personne) }}} * http://127.0.0.1:8000/admin/ * annuaire/models.py {{{ def __unicode__(self): return "" # coder ici la chaîne unicode désirée que l'on veut retourner }}} ''ajouter des attributs (des champs) et des méthodes à nos modèles existants'' * Personne.prenom * Personne.date_naissance * Etablissement.sigle ''Si south est installé, créer et appliquer la migration :'' {{{ python manage.py schemamigration annuaire --auto }}} South 0.6 {{{ python manage.py startmigration annuaire nom_migration --auto }}} {{{ python manage.py migrate annuaire }}} ''Sinon : '' * supprimer carto.db * (re)création de la base de DB pour avoir tables avec même structure que nos modèles modifiés {{{ python manage.py syncdb }}} * annuaire/models.py * ajouter une relation entre nos Etablissement et Personne * Personne.universite * modifier la base de données en conséquence : * south : créer et appliquer la migration * autre : supprimer la DB et syncdb * ajouter quelques Etablissements et Personnes dans l'admin === Backend pimpé : ModelAdmin === https://docs.djangoproject.com/en/1.4/ref/contrib/admin/ * annuaire/admin.py * classes EtablissementAdmin, PersonneAdmin ''héritent de ModelAdmin'' {{{ class EtablissementAdmin(admin.ModelAdmin): pass class PersonneAdmin(admin.ModelAdmin): pass }}} * enregistrer Modele avec ModeleAdmin {{{ admin.site.register(Etablissement, EtablissementAdmin) admin.site.register(Personne, PersonneAdmin) }}} * config ModeleAdmin {{{ list_display search_fields list_filter }}} * plus? https://docs.djangoproject.com/en/1.4/ref/contrib/admin/ * fields * fieldsets * ... === Sources finales === * Django 1.4 * [[Ateliers/Django/Frontend/Support?action=AttachFile&do=get&target=carto_1_1_backend_final.tar.gz|Django 1.1.1]] ---- == CONCLUSION : POUR CONTINUER == * Autres aspects non couverts (quelques uns) * frontend (urls.py, views.py, ORM, templates) * héritage de templates * URL avec paramètres * fichiers statiques : CSS, images et js * connexion utilisateur * permissions et décorateurs * manage.py inspectdb * fixtures : données initiales et de test https://docs.djangoproject.com/en/1.4/howto/initial-data/ * manage.py test * forms * generic views * templates : tags, filtres * Mailing list des utilisateurs Django : http://groups.google.com/group/django-users * Channel IRC #django : irc://irc.freenode.net/django * Contribs, plugins https://docs.djangoproject.com/en/dev/ref/contrib/ * reversion * Autre : pypi http://pypi.python.org/ * Savourez! ----