📚 Cheatsheet

Une collection organisée de snippets de code pour accélérer votre développement. Parcourez, recherchez et copiez en un clic.

Snippets 8

Retour
Afficher la pagination dans un template
Intermédiaire
<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="?page={{ page_obj.previous_page_number }}">précédent</a>
    {% endif %}
    <span>Page {{ page_obj.number }} sur {{ page_obj.paginator.num_pages }}.</span>
    {% if page_obj.has_next %}
        <a href="?page={{ page_obj.next_page_number }}">suivant</a>
    {% endif %}
</div>
Boucle 'for' dans un template
Facile
<ul>
{% for article in articles %}
    <li>{{ article.titre }}</li>
{% endfor %}
</ul>
Condition 'if' dans un template
Facile
{% if user.is_authenticated %}
    <p>Bonjour, {{ user.username }}.</p>
{% else %}
    <p>Bonjour, visiteur.</p>
{% endif %}
Pagination dans une vue fonction
Avancé
from django.core.paginator import Paginator

def liste(request):
    liste_objets = MaClasse.objects.all()
    paginator = Paginator(liste_objets, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'liste.html', {'page_obj': page_obj})
Rendre un template
Facile
# views.py
from django.shortcuts import render

def liste_articles(request):
    articles = Article.objects.all()
    return render(request, 'monapp/liste_articles.html', {'articles': articles})
Utiliser un fichier statique dans un template
Facile
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
Utiliser un template de base (héritage)
Facile
{# base.html #}
<body>
    {% block content %}{% endblock %}
</body>

{# page.html #}
{% extends 'base.html' %}
{% block content %}
    <p>Contenu de la page.</p>
{% endblock %}
Vue simple basée sur une fonction
Facile
# views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("<h1>Bonjour, Django !</h1>")