Django todo list
This content is not available in your language yet.
Initialisation du projet
-
Démarrage de l’envrionnement Python :
Dans le répertoire
root
, nommébackend
pour ce projet.Fenêtre de terminal python3 -m venv envsource env/bin/activate -
Installation de la dernière version de Django :
Fenêtre de terminal pip install django -
Création du projet, nommé
task_manager
:Fenêtre de terminal django-admin startproject task_manager . -
Démarrage du serveur :
Fenêtre de terminal python manage.py runserver
Création de l’application
-
Création de l’application, nommée
todolist
:Fenêtre de terminal python manage.py startapp todolist -
Configuration l’application dans le projet :
Modification du fichier
task_manager/settings.py
, dans la sectionINSTALLED_APPS
.task_manager/settings.py ...INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','todolist']... -
Modélisation des données :
Modification du fichier
todolist/models.py
, définition du modèle detodolist
.todolist/models.py from django.db import modelsclass Task(models.Model):title = models.CharField(max_length=200)description = models.TextField(blank=True)completed = models.BooleanField(default=False)due_date = models.DateField()assigned_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)def __str__(self):return self.title -
Enregistrement du modèle :
Modification du fichier
todolist/admin.py
pour y ajouter l’enregistrement du modèle Todo.todolist/admin.py from django.contrib import adminfrom .models import Task@admin.register(Task)class TaskAdmin(admin.ModelAdmin):list_display = ('title', 'description', 'completed', 'due_date', 'assigned_to' ,'created_at', 'updated_at')list_filter = ('completed', 'due_date', 'assigned_to')search_fields = ('title', 'description') -
Application des migrations :
Vous pourrez démarrer le projet pour vérifier son bon fonctionnement avec la commande suivante.
Fenêtre de terminal python manage.py makemigrationspython manage.py migrate
Configuration de l’interface /admin
-
Création d’un super utilisateur
Renseigner un nom d’utilisateur, une adresse e-mail et un mot de passe.
Fenêtre de terminal python manage.py createsuperuser
Affichage des tâches triées par date d’échéance
-
Création de la vue pour afficher la liste des tâches
Modification du fichier
todolist/views.py
.todolist/views.py from django.shortcuts import renderfrom .models import Taskdef task_list(request):tasks = Task.objects.all().order_by('due_date')return render(request, 'todolist/task_list.html', {'tasks': tasks}) -
Création du template
Création du fichier
todolist/templates/task_list.html
.todolist/templates/task_list.html <h1>Liste des tâches</h1><table><thead><tr><th>Titre</th><th>Description</th><th>Attribué à</th><th>Date d'échéance</th><th>Statut</th></tr></thead><tbody>{% for task in tasks %}<tr><td>{{ task.title }}</td><td>{{ task.description }}</td><td>{{ task.assigned_to }}</td><td>{{ task.due_date }}</td><td>{{ task.completed|yesno:"Terminé,En cours" }}</td></tr>{% endfor %}</tbody></table> -
Ajouter de l’URL correspondante
Ajout d’une route pour afficher la liste des tâches dans
task_manager/urls.py
.task_manager/urls.py from django.contrib import adminfrom django.urls import pathfrom todolist import viewsurlpatterns = [path('admin/', admin.site.urls),path('tasks/', views.task_list, name='task_list'),]La page est maintenant accessible à l’url,
<url>/tasks/
Filtrage des tâches
-
Installation de Django Filtrage
Fenêtre de terminal pip install django-filter -
Création d’un filtre personnalisé
todolist/filters.py import django_filtersfrom .models import Taskclass TaskFilter(django_filters.FilterSet):class Meta:model = Taskfields = {'title': ['icontains'],'assigned_to': ['exact'],'completed': ['exact'],'due_date': ['gte', 'lte'],} -
Modification de la vue pour utiliser les filters
todolist/views.py from django.shortcuts import renderfrom django_filters.views import FilterViewfrom .models import Taskfrom .filters import TaskFilterdef task_list(request):tasks = Task.objects.all().order_by('due_date')return render(request, 'task_list.html', {'tasks': tasks})task_filter = TaskFilter(request.GET, queryset=Task.objects.all().order_by('due_date'))return render(request, 'task_list.html', {'filter': task_filter}) -
Mise à jour du template
<h1>Liste des tâches</h1><form method="get">{{ filter.form.as_p }}<button type="submit">Rechercher</button></form><table><thead><tr><th>Titre</th><th>Description</th><th>Attribué à</th><th>Date d'échéance</th><th>Statut</th></tr></thead><tbody>{% for task in tasks %}{% for task in filter.qs %}<tr><td>{{ task.title }}</td><td>{{ task.description }}</td><td>{{ task.assigned_to }}</td><td>{{ task.due_date }}</td><td>{{ task.completed|yesno:"Terminé,En cours" }}</td></tr>{% endfor %}</tbody></table>
Pagination des tâches
-
Ajouter la pagination dans la vue
todolist/views.py from django.shortcuts import renderfrom django_filters.views import FilterViewfrom .models import Taskfrom .filters import TaskFilterfrom django.core.paginator import Paginatordef task_list(request):task_filter = TaskFilter(request.GET, queryset=Task.objects.all().order_by('due_date'))paginator = Paginator(task_filter.qs, 10)page_number = request.GET.get('page')page_obj = paginator.get_page(page_number)return render(request, 'task_list.html', {'filter': task_filter})return render(request, 'task_list.html', {'filter': task_filter, 'page_obj': page_obj}) -
Modification du template
todolist/templates/task_list.html <div class="pagination"><span class="step-links">{% if page_obj.has_previous %}<a href="?page=1">« première</a><a href="?page={{ page_obj.previous_page_number }}">précédente</a>{% endif %}<span>Page {{ page_obj.number }} de {{ page_obj.paginator.num_pages }}</span>{% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}">suivante</a><a href="?page={{ page_obj.paginator.num_pages }}">dernière »</a>{% endif %}</span></div>