Ceci est une ancienne révision du document !
Créer un environnement virtuel :
python3 -m venv venv
Ne pas oublier de l'activer :
. venv/bin/activate
Installer Django :
pip install django
Vérifier l'installation :
python -m django --version 3.2.9
⇒ Au moment d'écrire ces lignes c'est la version 3.2.9 qui est installée.
django-admin startproject monsite
La structure de base du projet est créée dans un dossier monsite :
./monsite ├── manage.py └── test1 ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
cd monsite/ .manage.py runserver
Visiter la page http://localhost:8000
Un projet est composé de plusieurs applications.
Création d'une application nommée blog dans le projet monsite :
./manage.py startapp blog
L'application est créée dans un sous-dossier au même niveau que le projet :
./monsite ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── manage.py └── monsite ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
La vue est une fonction dans le views.py de l'application :
from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('<h1>Blog Home</h1>')
Ajouter la route dans le urls.py de l'application :
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), ]
Ensuite ajouter la route de base de l'application dans le urls.py du projet :
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ]