Outils pour utilisateurs

Outils du site


python:django:application

Application

Un projet est composé de plusieurs applications.

Ajouter une nouvelle application

Création d'une application nommée blog dans le projet website :

cd /home/marc/prg/django_project/website
python manage.py startapp blog

L'application est créée dans un sous-dossier au même niveau que le projet :

/home/marc/prg/django_project$ tree -L 3
.
├── venv
│   └── ...
│
└── website
    ├── blog
    │   ├── admin.py
    │   ├── apps.py
    │   ├── __init__.py
    │   ├── migrations
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── db.sqlite3
    ├── manage.py
    └── website
        ├── asgi.py
        ├── __init__.py
        ├── __pycache__
        ├── settings.py
        ├── urls.py
        └── wsgi.py

Éditer le fichier settings.py du projet pour y ajouter l'application “blog” :

./website/settings.py
INSTALLED_APPS = [
    ...
    'blog'
]

Ajouter une vue et une route

La vue est une fonction dans le views.py de l'application :

./website/blog/views.py
from django.http import HttpResponse
 
def home(request):
    return HttpResponse('<h1>Blog Home</h1>')

Ajouter la route dans le urls.py de l'application :

./website/blog/urls.py
from django.urls import path
from blog import views
 
urlpatterns = [
    path('', views.home, name='blog-home'),
]

Ensuite inclure les routes de l'application dans le urls.py du projet :

./website/website/urls.py
from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]

Visiter la page http://localhost:8000/blog/

python/django/application.txt · Dernière modification: 2023/12/09 04:45 par marclebrun